![](/img/trans.png)
[英]How to add NSMutableArray as objectAtIndex for NSMutableArray
[英]How to add observer on NSMutableArray?
我搜索了很多,但沒有找到有用的代碼或教程。
在我的應用程序中,我有一個可變數組,每60秒更新一次。
數組中的對象由多個視圖控制器中的表視圖顯示。
我只想在數組中的值更改或更新時自動重新加載表視圖。
為此,我想在可變數組上添加觀察者,即當數組中的值發生變化時,它應該調用特定的方法,例如
-(void)ArrayUpdatedNotification:(NSMutableArray*)array
{
//Reload table or do something
}
提前致謝。
您可以使用訪問器方法將數組抽象為數據容器類,然后使用鍵值觀察來觀察何時更改了支持容器對象的數組(您無法直接在NSArray
上使用KVO)。
下面是一個用作數組頂部抽象的類的簡單示例。 您可以使用其insertObject:inDataAtIndex:
和removeObjectFromDataAtIndex:
方法,而不是直接訪問with addObject:
和removeObject:
.
// DataContainer.h
@interface DataContainer : NSObject
// Convenience accessor
- (NSArray *)currentData;
// For KVC compliance, publicly declared for readability
- (void)insertObject:(id)object inDataAtIndex:(NSUInteger)index;
- (void)removeObjectFromDataAtIndex:(NSUInteger)index;
- (id)objectInDataAtIndex:(NSUInteger)index;
- (NSArray *)dataAtIndexes:(NSIndexSet *)indexes;
- (NSUInteger)countOfData;
@end
// DataContainer.m
@interface DataContainer ()
@property (nonatomic, strong) NSMutableArray *data;
@end
@implementation DataContainer
// We'll use automatic notifications for this example
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
{
if ([key isEqualToString:@"data"]) {
return YES;
}
return [super automaticallyNotifiesObserversForKey:key];
}
- (id)init
{
self = [super init];
if (self) {
// This is the ivar which provides storage
_data = [NSMutableArray array];
}
return self;
}
// Just a convenience method
- (NSArray *)currentData
{
return [self dataAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self countOfData])]];
}
// These methods enable KVC compliance
- (void)insertObject:(id)object inDataAtIndex:(NSUInteger)index
{
self.data[index] = object;
}
- (void)removeObjectFromDataAtIndex:(NSUInteger)index
{
[self.data removeObjectAtIndex:index];
}
- (id)objectInDataAtIndex:(NSUInteger)index
{
return self.data[index];
}
- (NSArray *)dataAtIndexes:(NSIndexSet *)indexes
{
return [self.data objectsAtIndexes:indexes];
}
- (NSUInteger)countOfData
{
return [self.data count];
}
@end
我們這樣做的原因是我們現在可以觀察對底層數組所做的更改。 這是通過Key Value Observing完成的 。 顯示了一個實例化和觀察數據控制器的簡單視圖控制器:
// ViewController.h
@interface ViewController : UIViewController
@end
// ViewController.m
@interface ViewController ()
@property (nonatomic,strong) DataContainer *dataContainer;
@end
@implementation ViewController
static char MyObservationContext;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Instantiate a DataContainer and store it in our property
_dataContainer = [[DataContainer alloc] init];
// Add self as an observer. The context is used to verify that code from this class (and not its superclass) started observing.
[_dataContainer addObserver:self
forKeyPath:@"data"
options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew)
context:&MyObservationContext];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// Check if our class, rather than superclass or someone else, added as observer
if (context == &MyObservationContext) {
// Check that the key path is what we want
if ([keyPath isEqualToString:@"data"]) {
// Verify we're observing the correct object
if (object == self.dataContainer) {
NSLog(@"KVO for our container property, change dictionary is %@", change);
}
}
}
else {
// Otherwise, call up to superclass implementation
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Insert and remove some objects. Console messages should be logged.
[self.dataContainer insertObject:[NSObject new] inDataAtIndex:0];
[self.dataContainer insertObject:[NSObject new] inDataAtIndex:1];
[self.dataContainer removeObjectFromDataAtIndex:0];
}
- (void)dealloc
{
[_dataContainer removeObserver:self forKeyPath:@"data" context:&MyObservationContext];
}
@end
運行此代碼時,視圖控制器會觀察到對數據的三次更改並將其記錄到控制台:
KVO for our container property, change dictionary is {
indexes = "<NSIndexSet: 0x8557d40>[number of indexes: 1 (in 1 ranges), indexes: (0)]";
kind = 2;
new = (
"<NSObject: 0x8557d10>"
);
}
KVO for our container property, change dictionary is {
indexes = "<NSIndexSet: 0x715d2b0>[number of indexes: 1 (in 1 ranges), indexes: (1)]";
kind = 2;
new = (
"<NSObject: 0x71900c0>"
);
}
KVO for our container property, change dictionary is {
indexes = "<NSIndexSet: 0x8557d40>[number of indexes: 1 (in 1 ranges), indexes: (0)]";
kind = 3;
old = (
"<NSObject: 0x8557d10>"
);
}
雖然這有點復雜(並且可以更多地涉及),但這是自動通知可變數組的內容被更改的唯一方法。
可以做的是 - 更新陣列后發送通知(NSNotificationCenter),所有控制器都會收到此通知。 收到通知后,控制器應該執行[tableview reloaddata]。
代碼示例 :
// Adding an observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable:) name:@"arrayUpdated" object:nil];
// Post a notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"arrayUpdated" object:nil];
// the void function, specified in the same class where the Notification addObserver method has defined
- (void)updateTable:(NSNotification *)note {
[tableView reloadData];
}
如果你想使用閃亮的塊,你可以這樣做
// Create an instance variable for your block holder in your interface extension
@property (strong) id notificationHolder;
// Listen for notification events (In your TableView class.
self.notificationHolder = [[NSNotificationCenter defaultCenter] addObserverForName:@"NotificationName"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"Received notification");
}];
然后在dealloc(或當你不再使用它時)
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self.notificationHolder];
}
然后在其他一些班級
// Send a notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:nil];
詢問是否有不清楚的事情! 希望能幫助到你!
編輯由於評論
“ YourEvent ”是通知的名稱,這意味着您可以將其命名為您想要的任何名稱。 (也許“ UpdateArrayNotification可能是一個好名字?)
需要考慮的事項:請注意,您可以為同一通知提供多個觀察者。 這意味着所有觀察者都會搶斷一個“帖子”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.