当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Update UI from another class

问题描述:

I am trying to separate my GUI and my Logic...For example, i have one class which calculates something (calc.h/calc.m). And i have my GUI (viewController.h/viewController.m)...Now i want to update one Element of the GUI from another class... I already tried it with a Singleton, like this:

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;

}

}

But it doest work...

UPDATE:

in my 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"];

}

}

And in my other class i post the notification like this:

[[NSNotificationCenter defaultCenter]

postNotificationName:@"UpdateDownloadLabel"

object:nil userInfo:info];

But it doesn't work...

网友答案:

That's not a proper use of a singleton. If you need to notify your UI from your model you have these options:
- delegation
- Local Notification
- KVO
The general rule is to keep your logic decoupled from your presentation, therefore your calc class shouldn't really know that a label named download exists.

网友答案:

Example: How to use notification.

  • In classA.h file

extern NSString * const ClassADidViewNotification;

  • In classA.m file

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);
       }
 ];

Post Notification:-

ClassB.m
[[NSNotificationCenter defaultCenter] postNotificationName: ClassADidViewNotification object:nil];
分享给朋友:
您可能感兴趣的文章:
随机阅读: