开发者

addObserver questions, try to check if data is loaded

开发者 https://www.devze.com 2023-01-05 04:37 出处:网络
I have a ViewController that initializes another class that loads data into a mutable array and saves it as a property on itself.

I have a ViewController that initializes another class that loads data into a mutable array and saves it as a property on itself.

here is my ViewController init code:

-(id) initWithCollectionID:(NSString *)aCollectionID {
    if (self = [super init]){
        col开发者_如何学GolectionID=aCollectionID;
        dataSource = [[CollectionListDataSource alloc] initWithCollectionID:collectionID];
    }
    return self;
}

once dataSource has loaded all of the data into it's property dataSource.collectionItems I set dataSource.loaded = @"true";

how do I use addObserver to watch that value and fire off a function in my ViewController?

something like this I'd assume:

[self addObserver:dataSource forKeyPath:@"loaded" options:NSKeyValueChangeNewKey context:nil];

Then what do I do?


As your code stands now, it will pause until the data is loaded regardless of whether you use notifications or not. It will not progress past:

dataSource = [[CollectionListDataSource alloc] initWithCollectionID:collectionID];

...until the CollectionListDataSource object has completed its own initialization (which I presume also means the loading its data) and returns an instance of itself.

If you want the CollectionListDataSource object to load while the view controller keeps on initializing, you will need to put the CollectionListDataSource object on another thread. However, you can't have an attribute object running on separate thread.

You seldom need to jump through such hoops. Unless this array is very large (10k+ objects) you most likely don't have to worry about. In most cases, you need the data before the view can function anyway so there's no point in letting the view go on without the data.

If you do need actually need to observe an attribute of another object, see Key-Value Programming Guide: Registering For Key-Value Observing for details.

0

精彩评论

暂无评论...
验证码 换一张
取 消