我正在尝试将REST连接模型存储在单个对象中,这样我就不必一次又一次地使用它。这是我创建的模型:
//RestModel.h
#import "ASIHTTPRequest.h"
@interface RestModel : NSObject{
NSString* _baseUrl;
NSString* _modelUrl;
}
@property (nonatomic, retain) NSString* modelUrl;
- (id)initWithModel:(NSString*)model;
- (NSDictionary*)getById:(NSInteger*)ident;
- (NSDictionary*)getAll;
@end
//RestModel.m
#import "RestModel.h"
@implementation RestModel
@synthesize modelUrl = _modelUrl;
- (id)init
{
self = [super init];
if (self) {
_baseUrl = @"http://myRESTurl.com";
}
return self;
}
- (id)initWithModel:(NSString*)model
{
self = [super init];
if (self) {
_baseUrl = @"http://myRESTurl.com";
self.modelUrl = [NSString stringWithFormat:@"%@/%@/", _baseUrl, model];
}
return self;
}
- (NSDictionary*)HTTPRequest:(NSURL*)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if(!error){
NSData *responseData = [request responseData];
NSString *errorDesc = nil;
NSPropertyListFormat format;
[error release];
[request release];
return (NSDictionary*)[NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
}else{
NSLog(@"%@", error);
return nil;
}
}
- (NSDictionary*)getById:(NSInteger*)ident
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", self.modelUrl, ident]];
return [self HTTPRequest:url];
}
- (NSDictionary*)getAll
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", self.modelUrl]];
return [self HTTPRequest:url];
}
- (void)dealloc
{
[_modelUrl release];
// [_responseData release];
// [_responseDict release];
[super dealloc];
}
@end
编辑:现在它没有崩溃,但我的本地NSDictionary的计数为0.我在我的控制器中的-viewDidLoad中调用以下内容:
RestModel* rm = [[RestModel alloc] initWithModel:@"user"];
self.dict = [rm getAll];
[rm release];
我在整个控制器中种植了[self.dict count]的NSLog。它始终为0.调用RestModel rm,调用函数(再次调用更多NSLog),但没有数据。有什么想法吗?
答案 0 :(得分:2)
[error release];
[request release];
这些应该是自动释放的对象,因为你通过便捷方法获得它们,因此明确释放它们会使你的应用程序崩溃。
答案 1 :(得分:1)
NSInteger不是一个对象,所以没有必要使用NSInteger *传递它,当然你不想使用%@格式说明符。相反,试试这个:
- (NSDictionary*)getById:(NSInteger)ident
{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%d", self.modelUrl, ident]];
return [self HTTPRequest:url];
}