[英]Access data from AppDelegate in ViewController.
我是一名初學程序員,也是這個網站的新手,我在嘗試之前嘗試尋找解決方案,但是如果之前已經問到這個問題就很難對其進行措辭。
我正在使用Parse,基本上我現在的主要目標是在標簽中顯示應用程序中的用戶數量。
在我的AppDelegate.m中
PFQuery *userCountQuery = [PFUser query];
[userCountQuery countObjectsInBackgroundWithBlock:^(int userCount, NSError *error) {
if (!error) {
// The count request succeeded. Log the count
NSLog(@"There are %d users", userCount);
} else {
// The request failed
}
}];
該代碼在我的控制台中得到正確的數字,現在我只是將此變量放入視圖控制器以與標簽一起使用。 有一個簡單的方法可以做到這一點,還是我從一開始就完成這個缺陷的方法?
實際上你在你的app委托中創建了一個getter / setter,但這不是正確的開發方式。 我的意思是你應該在你的APP中有更多的層,比如經理,來處理這些數據
在這里你可以先試着看看它是否有效
我的結構將允許您稍后將代碼從appDelegate移動到任何其他類/地方,因為您可能在學習期間很快使用getter / setter;)
myAppDelegate.h
@interface myAppDelegate : NSObject <UIApplicationDelegate>
{
}
----------
myAppDelegate.m
@interface myAppDelegate()
@end
@implementation myAppDelegate
- (int)getProperNumber
{
return properNumber;
}
----------
ViewController.m
mAppDelegate * appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
int count = [appDelegate getProperNumber];
干杯。
我假設你現在在AppDelegate中有一個方法與你的代碼段,就像這樣:
@interface AppDelegate {
...
- (void)countUser;
}
然后您可以將該方法更改為:
- (void)countUserWithSuccessfulBlock:(void (^)(int))successfulBlock
{
PFQuery *userCountQuery = [PFUser query];
[userCountQuery countObjectsInBackgroundWithBlock:^(int userCount, NSError *error) {
if (!error) {
// The count request succeeded. Log the count
NSLog(@"There are %d users", userCount);
successfulBlock(userCount);
} else {
// The request failed
}
}];
}
然后從你的ViewController:
AppDelegate* appDelegate = (AppDelegate*) [UIApplication shareApplication].delegate;
[appDelegate countUserWithSuccessfulBlock:^(int result) {
//Display to your label;
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.