REST接続モデルを単一のオブジェクトに格納しようとしているため、何度も繰り返し使用する必要がありません。カスタムNSObjectクラスを使用してiPhoneアプリケーションで繰り返しコードを単純化するときのトラブル
//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が呼び出され、関数は呼び出されます(もう一度NSLogs)が、データは呼び出されません。何か案は?
これは現在クラッシュしていませんが、NSDictionaryは空です。私は-viewDidLoadでロードしていて、NSDictionaryのテーブルのNSLogを置くこともできます。tableView numberOfRowsInSection:セクションは0です。RestModelを解放しないといいですか?これは私が-viewDidLoadでロードする方法です:RestModel * rm = [[RestModel alloc] initWithModel:@ "user"]; self.dict = [rm getAll]; [rm release]; – rnystrom
それを解放することは大丈夫です。あなたのHTTPRequestメソッドにログインしようとしてください... – Macmade
心配しないで、あなたはそれを釘付け!カウントの問題は私自身の責任でした。あなたは揺れる。 – rnystrom