从另一个类更新UI

时间:2014-03-14 14:23:55

标签: ios iphone objective-c ios7

我正在尝试将我的GUI和逻辑分开...例如,我有一个计算内容的类(calc.h / calc.m)。我有我的GUI(viewController.h / viewController.m)...现在我想从另一个类更新GUI的一个元素...我已经尝试使用Singleton,如下所示:

calc.m:

viewController *con = [viewController sharedInstance];
con.download.text = @"It Works";

viewController.m:

+ (id)sharedInstance {
static id sharedInstance;
@synchronized(self) {
    if (!sharedInstance)
        sharedInstance = [[viewController alloc] init];
    return sharedInstance;
}
}

但它不起作用......

更新:

在我的ViewController中

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(receiveNotification:)
                                             name:@"UpdateDownloadLabel"
                                           object:nil];

- (void) receiveNotification:(NSNotification *) notification
{

NSDictionary* userInfo = notification.userInfo;

if ([[notification name] isEqualToString:@"Update"])
{
    download.text = [userInfo valueForKey:@"Test"];
}
}

在我的其他课程中,我发布了这样的通知:

[[NSNotificationCenter defaultCenter]
 postNotificationName:@"UpdateDownloadLabel"
 object:nil userInfo:info];

但它不起作用......

2 个答案:

答案 0 :(得分:6)

这不是单身人士的正确用法。如果您需要从模型中通知您的UI,您可以选择以下选项:
- delegation
- Local Notification
- KVO
一般规则是让您的逻辑与您的演示文稿分离,因此您的calc类不应该真正知道名为download的标签存在。

答案 1 :(得分:0)

示例:如何使用通知。

  • 在classA.h文件中

extern NSString * const ClassADidViewNotification;

  • 在classA.m文件中

NSString * const ClassADidViewNotification = @“ClassADidViewNotification”;

Register for notification in classA.m :-     
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  [center addObserverForName: XXFooDidBarNotification
                      object:nil
                       queue:nil
                  usingBlock:^(NSNotification *notification)
       {
          NSLog(@"notification.object: %@", notification.object);
       }
 ];

发布通知: -

ClassB.m
[[NSNotificationCenter defaultCenter] postNotificationName: ClassADidViewNotification object:nil];
相关问题