Reputation: 5927
Hey, I'm a beginner in Objective C, and my .NET and Java years have rusted my memory management skills, so it's very likely I'm missing something here.
I am building an iPad app. The main view is a SplitView with a TableView on the left, and the detail view contains another TableView. The loading of the latter with data has been commented out in an attempt to single out my problem.
The app seems to work fine (has to fetch data from a .NET WS and parse it into the table), but at random times I receive a BAD_ACCESS or a "selector not recognized" errors.
The selector not recognized error I get here:
-(void) connection:(NSURLConnection *) connection
didReceiveResponse:(NSURLResponse *) response {
[webData setLength: 0];
}
This piece of code I'm sure most of you know about, I got it from all samples I found online and in books to send a web request.
Beats me why it says it does not recognize the setLength selector, webData is defined as
NSMutableData *webData;
Any ideas?
Thanks.
Upvotes: 0
Views: 453
Reputation: 3919
If you do not allocate your webData object either with
NSMutableData* webData = [[NSMutableData alloc] initWithCapacity:2048];
or
NSMutableData* webData = [[NSMutableData data] retain];
then the webData object will most likely be autoreleased during one of the context switches from the NSURLConnection message that you allocated it in (probably connection:didReceiveData:
) to the connection:didReceiveResponse:
message.
Any object that you do not alloc
or explicitly retain
is likely to be deallocated during scope changes, even if it is a member variable of your class.
Upvotes: 1
Reputation: 13876
Seems to be very usual (not only beginners) error, when connection is not cancels in dealloc
or viewWillDisappear
. When you are leaving the controller, you should cancel all connection, timers, etc, created by the controller, to prevent them from calling delegate methods or selectors on deallocated controller objects.
Upvotes: 1
Reputation: 185681
Most likely you aren't creating the NSMutableData correctly. I expect you have code that looks like
webData = [NSMutableData data];
This is going to give you an autoreleased object, and yet you're storing it in an ivar. You need to take ownership of the object when storing it in an ivar. In your case, the simplest way is just to skip the convenience method and go with alloc/init:
webData = [[NSMutableData alloc] init];
For more details, read the Memory Management Programming Guide.
Upvotes: 1
Reputation: 39905
It looks like webData is being deallocated and replaced with some other object. Make sure you retain it if you don't use alloc/init or mutableCopy to get it.
Upvotes: 0