在另一个文件中使用的NSString对象显示的值始终为null



我有两个.m文件。我在另一个.m上使用了nsstring对象,它总是null。

//postputgetFunction.h

     @property(retain,nonatomic) IBOutlet NSMutableString *postRegisterResponseUserId;

//postputgetFunction.m

  @synthesize postRegisterResponseUserId;
    -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
   {
if ([flag isEqualToString:@"post"])
{
    NSLog(@"Post received data here.....");
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    postRegisterResponseName=[dict valueForKey:@"Name"];
    postRegisterResponseSuccess=[dict valueForKey:@"Success"];
    postRegisterResponseUserId=[dict valueForKey:@"UserId"];
    NSLog(@"ReceiveData :Name : %@ n Success : %@ n UserId : %@",postRegisterResponseName,postRegisterResponseSuccess,postRegisterResponseUserId);
   //Above statement display the value properly..........
    flag=Nil;
}
}

但我在另一个.m文件中使用。。。在这个.m文件中,它显示的值为null。。像这样,//验证.h

    #import "PostPutGetFunction.h"
    @property (retain, nonatomic) PostPutGetFunction *postputgetFunction;

//验证.m

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
postputgetFunction=[[PostPutGetFunction alloc]init];
}
- (IBAction)verificationBtnClick:(id)sender
{
    NSLog(@"%@",postputgetFunction.postRegisterResponseUserId);
    //here its always shown NULL ... i didnt get the value here ...
}

在其他.m文件的viewDidLoad方法中,您使用分配和初始化PostPutGetFunction

postputgetFunction=[[PostPutGetFunction alloc]init];

这就是为什么PostPutGetFunction类NSMutableString*postRegisterResponseUserId中定义的变量初始化为Null的原因。可以使用代理在两个控制器之间传递数据。或者,您可以将userID存储在NSUserDefault类中,如下面的

**First Part**
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *name =[dict valueForKey:@"Name"];
NSString *success=[dict valueForKey:@"Success"];
NSString *userid =[dict valueForKey:@"UserId"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
[defaults setObject:name forKey:@"NAME"];
[defaults setObject:success forKey:@"SUCCESS"];
[defaults setObject:userid forKey:@"USERID"];
[defaults synchronize];

为了检索另一个类中的值,m使用下面的代码

**Second Part**
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
NSString *name = [defaults objectForKey:@"NAME"];
NSString *success = [defaults objectForKey:@"SUCCESS"];
NSString *userid = [defaults objectForKey:@"USERID"];

此外,您不将IBOutlet用于NSMutableString类型,而是用于UI控件类型,如Below

您正在声明PostPutGetFunction的新对象,并且确定值postRegisterResponseUserId将为空

如果你想实现这一点,你必须使用委派,看看这个答案

最新更新