문제

I have UIViewController with strong DataController containing and managing a list of items (itemsList). In the initialization method of the latter, I read items from a file, get additional information for each of these via web services (and ASIHTTPRequest) and put the items in a list which is then assigned to the itemsList property.

With synchronous requests everything works fine but I need an asynchronous implementation. I did it and now my items get deallocated (the data controller not), following the delegates for the requests etc disappear as well. How can I keep the items alive?

In my data controller:

-(id)initDataController
{
self = [super init];
if (self)
{
    NSMutableArray *myList = [[NSMutableArray alloc] init];

    // Read items from file ...

    for (NSString *itemName in items) {
        MyItem *item = [[MyItem alloc] initWithParam:itemName];
        // Here the item has already been deallocated?!
        if (item) {
            [myList addObject:item];
        }
    }
    _itemsList = myList;
    return self;
}
return nil;
}

In MyItem class there is just standard request to the server and initialization. I think the problem should be in some missing strong/retain but I have no idea where I should put it.

EDIT:

The definition of the list:

@property (nonatomic, copy) NSMutableArray *itemsList;

What I am wondering is that the items are nil even before I can put them into the list... So I tried making the property strong instead of copy but nothing changes.

도움이 되었습니까?

해결책

MyItem *item = ...

This local variable forms a strong reference. If initWithParam: returns an object (not nil), there'w no way it can be deallocated before being added to the list (which creates another strong reference).

Please take note that your property declaration is flawed:

@property (nonatomic, copy) NSMutableArray *itemsList;

The copy attribute does not go well with a mutable object type: When the property is assigned, the synthesized setter calls copy on it, which creates an immutable copy of the array and assigns that. This contradicts the type of the property.

Here's in fact a nice opportunity for another helpful clang compiler warning: Properties cannot be declared copy when their type conforms to NSMutableCopying. clang team, are you hearing?.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top