如何使用NSNotificationCenter传输数据ViewControllers / classes?

时间:2013-06-24 03:26:20

标签: ios objective-c nsnotificationcenter

我有一个表视图控制器,它应该填充来自封装在store类中的数组的数据。该表需要通过方法table:numberOfRowsInSection:知道每个部分中有多少行。在这个方法中,我需要返回store实例中的数组大小。我最初通过使store成为单身人员来做到这一点,但被告知这是低效率的,并且使用NSNotificationCenter会更好。

据我所知,当另一个对象发布特定通知时,所有NSNotificationCenter都会触发某些对象中的方法。如何使用NSNotificationCenter将数组大小发送到表视图控制器?

3 个答案:

答案 0 :(得分:2)

你可以这样做:

...
// Send 
[[NSNotificationCenter defaultCenter] postNotificationName: SizeOfRrrayNotification
                                                    object: [NSNumber numberWithInteger: [array count]]];

...
// Subscribe
[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(sizeOfArray:)
                                             name: SizeOfRrrayNotification
                                           object: nil];

// Get size
- (void) sizeOfArray: (NSNotification*) notification
{
    NSNumber* sizeOfArray = (NSNumber*) notification.object;
    NSLog(@"size of array=%i",  [sizeOfArray integerValue]);
}

答案 1 :(得分:0)

发布通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyArraySize" object: [NSNumber numberWithInteger: [myArray count]]] userInfo:nil];

获取通知:

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

在要获取通知的viewController中添加此方法:

- (void) getSizeOfArray: (NSNotification*) notification
{
    NSNumber* myArraySize = (NSNumber*) notification.object;
}

您甚至可以通过“userInfo”发送更多数据,并使用notification.userInfo在选择器方法中获取该数据,但请记住其类型为“NSDictionary

希望这会对你有所帮助。

答案 2 :(得分:0)

计算数组大小的方法:

< ------通知发送方---------->

-(void)sizeOfArray{
   int size = [myArray count];
   NSMutableString *myString = [NSMutable string];
   NSString *str = [NSString stringwithFormat:@"%d",size];
   [myString apprndString:str];

//It is to be noted that NSNotification always uses NSobject hence the creation of mystring,instead of just passing size

   [[NSNotificationCenter defaultCenter] postNotificationName:@"GetSizeOfArray"      object:myString];
}

现在,一旦您发布了通知,请将其添加到您要发送数据的控制器的viewDidLoad方法

< ------通知接收方---------->

-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(get_notified:) name:@"GetSizeOfArray"  object:nil];

//The selector method should always have a notification object as its argument

 [super viewDidLoad];

}


- (void)get_notified:(NSNotification *)notif {
    //This method has notification object in its argument

    if([[notif name] isEqualToString:@"GetSizeOfArray"]){
       NSString *temp = [notif object];
       int size = [temp int value];

       //Data is passed.
        [self.tableView reloadData];  //If its necessary 

     }    
}

希望这有帮助。