I have the following Class:
—- .h file
#import <Foundation/Foundation.h>
#import "MapperProtocoll.h"
@interface ServiceRequest : NSObject {
}
@property (strong, nonatomic) NSString *url;
@property (strong, nonatomic) NSString *postData;
@property (strong, nonatomic) NSNumber *requestId;
@property (strong, nonatomic) id<ServiceMapperDelegate> mapper;
-(id)initWithUrl:(NSString *)url andWithPostdata:(NSString *)postData;
@end
——- .m file
#import "ServiceRequest.h"
@implementation ServiceRequest
@synthesize url = _url, postData = _postData, requestId = _requestId, mapper = _mapper;
-(id)initWithUrl:(NSString *)url andWithPostdata:(NSString *)postData {
if (self = [super init]) {
_url = url;
_postData = postData;
self.requestId = [NSNumber numberWithInt:-1]; // HERE IS THE PROBLEM
}
return self;
}
@end
Why does
self.requestId = [NSNumber numberWithInt:-1];
work but
_requestId = [NSNumber numberWithInt:-1];
throw a runtime error?
The class method
[NSNumber numberWithInt:-1]is returning an autoreleased value. When you use the synthesized setter method, the value gets retained by the setter. When you bypass the setter, there is no retain… So as soon as the autorelease pool is drained you have a dangling pointer.