0

您好,我是 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;

用户数据.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

用户数据.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
4

2 回答 2

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]];

为什么你使用字符串而不是浮点数?当您需要进行一些比较时,这不会让您的生活更轻松吗?

还要检查您是否为“myUser”分配了内存,也可能是这种情况。

于 2012-04-26T19:14:31.803 回答
0

正如尤金所说,你应该使用 valueForKey 而不是 objectForKey

另一件事是,正如 Apple 推荐的那样,每当您引用对象成员时,您可能都想使用属性和点表示法。管理内存通常对您有好处。

先前关于不在 -init() 中初始化字符串成员的答案是完全错误的,如果这引起了一些混乱,我对此深表歉意。

于 2012-04-26T19:18:49.330 回答