我對Objective-C編程有點新手,無法理解如何在一個方法中創建一個NSObject並在另一個方法中使用它。你如何使一個NSObject「全局」/可用於所有方法?
例如:
我有像名字,姓氏性質的UserObject。
@interface UserObject : NSObject
@property (nonatomic, retain) NSString *userID, *firstName, *lastName, *profilePic, *fullName, *email, *twitter, *followingCount, *followerCount;
@end
在我profileViewController.h我宣佈currentUser爲@property (retain, nonatomic) UserObject *currentUser;
現在,這裏的問題。我有這個IBAction爲
- (IBAction)followUser:(id)sender {
NSLog(currentUser.firstName);
}
接收來自服務器的JSON數據後,我開了一家叫做ConnectionDidFinishLoading和內部方法 - >
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *json = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *dataArray = [json JSONValue];
UserObject *currentUserData = [[UserObject alloc] init];
currentUserData.firstName = [dataArray objectForKey:@"first_name"];
currentUserData.lastName = [dataArray objectForKey:@"last_name"];
currentUser = currentUserData;
[dataArray release];
[json release];
[currentUserData release];
}
現在,這裏的問題。當我運行這個IBAction時,應用程序崩潰。
- (IBAction)followUser:(id)sender {
NSLog(@"%@",currentUser.firstName);
}
我敢肯定,這是因爲currentUser不適用於此方法。有沒有辦法使currentUser對象成爲全局的,這樣我就可以用任何方法來抓取它了?
'followUser'操作在'ProfileViewController.m'中,對不對? – 2012-04-07 17:54:31
yes在.h中聲明爲 - (IBAction)followUser:(id)sender;並且該動作在.m文件中。 – 2012-04-07 17:56:36
嗯,我的意思是這個' - (IBAction)followUser:(id)sender NSLog(@「%@」,currentUser.firstName); }''在'.m'文件中,對嗎? – 2012-04-07 17:57:55