您好我是iPhone开发的新手。 我尝试将NSDictionary中的移动数据添加到我创建的调用的数据成员中。 当我“setWeightMeasure”没有发生任何事情。
有什么建议吗?
不起作用的代码:
NSDictionary *responseBodyProfile = [responseBody objectFromJSONString];
NSLog(@"%@",responseBodyProfile);
// the output is :
"{ "profile": {"goal_weight_kg": "77.0000", "height_cm": "179.00",
"height_measure": "Cm", "last_weight_date_int": "15452",
"last_weight_kg": "99.0000", "weight_measure": "Kg" }}""
[responseBody release];
if (responseBodyProfile != nil ){
NSDictionary *profile =[responseBodyProfile valueForKey:@"profile"];
NSLog(@"%@\n",[profile objectForKey:@"weight_measure"]);// Output : "kg"
[self.myUser setWeightMeasure:[profile objectForKey:@"weight_measure"]];
NSLog(@"%@", [self.myUser WeightMeasure]); // Output : "(null)"
}
H档案:
@property (nonatomic, retain) UserData* myUser;
UserData.h:
#import <Foundation/Foundation.h>
@interface UserData : NSObject{
NSString* Weight;
NSString* Height;
NSString* GolWeight;
NSString* WeightMeasure;
}
@property (nonatomic, retain) NSString* Weight;
@property (nonatomic, retain) NSString* Height;
@property (nonatomic, retain) NSString* GolWeight;
@property (nonatomic, retain) NSString* WeightMeasure;
@end
UserData.m
#import "UserData.h"
@implementation UserData
@synthesize Weight, Height, GolWeight, WeightMeasure;
-(id)init{
self.Weight = @"0";
self.Height = @"0";
self.GolWeight = @"0";
self.WeightMeasure = @"0";
return self;
}
-(void)dealloc{
[Weight release];
[Height release];
[GolWeight release];
[WeightMeasure release];
[super dealloc];
}
@end
答案 0 :(得分:0)
在此行中使用valueForKey而不是objectForKey:
[self.myUser setWeightMeasure:[profile objectForKey:@"weight_measure"]];
像这样:
[self.myUser setWeightMeasure:[profile valueForKey:@"weight_measure"]];
您可能还想使用,因为这些值可以读作NSNumbers
[self.myUser setWeightMeasure:[[profile valueForKey:@"weight_measure"] stringValue]];
为什么你使用字符串而不是浮点数?当您需要进行一些比较时,这会不会让您的生活更轻松?
同时检查你是否为&#34; myUser&#34;分配了内存,也可能是这种情况。
答案 1 :(得分:0)
正如Eugene所提到的,你应该使用valueForKey而不是objectForKey
另一件事是,当你引用你的对象成员时,你可能想要使用属性和点符号,正如Apple建议的那样。管理记忆通常对你有好处。
关于不在你的-init()中初始化你的字符串成员的前一个答案是完全错误的,如果这会导致一些混乱,我为它道歉。