如何将 NSMutableArray 存储到 NSUserDefaults 并在 TableView 中显示结果?

发布于 2024-12-25 23:15:56 字数 5042 浏览 2 评论 0原文

我想将来自服务器的通知保存在我的应用程序中,并创建一个用户界面,使用户能够选择要阅读的通知(消息)。在预定方法中,我的客户端控制服务器内部的更改,并且通信采用 JSON 格式。我已经解析了它,并且也可以在 NSLog(@"....",..) 中看到结果。我还控制来自服务器的消息状态,如果状态等于 1,我将保存消息并向 TableView 添加一个节点。现在,任何人都可以帮助我了解如何在 NSMutableArray 中传输数据都到 NSUserDefaults 和 TableView 吗?如果您愿意,我也可以共享代码或 JSON 表示形式。 如果你能用一些代码解释一下那就更好了。谢谢

我决定分享一些我的代码,

因为我也在代码下写过,我想在 UITableView< 中显示 NSMutableArray /代码>

    `-(IBAction)Accept:(id)sender
    {   userName=[[NSString alloc] initWithString:userNameField.text ];
        [userNameField setText:userName];
        NSUserDefaults *userNameDef= [NSUserDefaults standardUserDefaults];
        [userNameDef setObject:userName forKey:@"userNameKey"];
        password =[[NSString alloc] initWithString:passwordField.text];
        [passwordField setText:password];
        NSUserDefaults *passDef=[NSUserDefaults standardUserDefaults];
        [passDef setObject:password forKey:@"passwordKey"];
        serverIP=[[NSString alloc] initWithString: serverField.text];
        [serverField setText:serverIP];
        NSUserDefaults *serverDef=[NSUserDefaults standardUserDefaults];
        [serverDef setObject:serverIP forKey:@"serverIPKey"];
        [userNameDef synchronize];
        [serverDef synchronize];
        [passDef synchronize];


    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                      message:@"Your User Informations are going to be sent to server. Do you accept?"
                                                     delegate:self
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:@"Cancel",  nil];
    [message show];
}



    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

        if([title isEqualToString:@"OK"])
        {
            if([userNameField.text isEqualToString:@""]|| [passwordField.text isEqualToString:@""] || [serverField.text length]<10) 
            {
                UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                                   message:@"Your User Informations are not defined properly!"
                                                                  delegate:nil
                                                         cancelButtonTitle:@"OK"
                                                         otherButtonTitles:  nil];

                [message1 show];


        [userNameField  resignFirstResponder];
            [passwordField resignFirstResponder];
            return;
        }
        //## GET code to here**
        NSString *str1=[@"?username=" stringByAppendingString:userNameField.text];
        NSString *str2=[@"&password=" stringByAppendingString:passwordField.text];
        NSString *str3=[str1 stringByAppendingString:str2];
        NSString *str4 =[@"http://" stringByAppendingString:serverField.text];


        NSURL *url=[NSURL URLWithString:[str4 stringByAppendingString:[@"/ipad/login.php" stringByAppendingString:str3]]];
        NSLog(@"%@\n",url);
        //get the url to jsondata
        NSData *jSonData=[NSData dataWithContentsOfURL:url];

        if (jSonData!=nil) {
            NSError *error=nil;
            id result=[NSJSONSerialization JSONObjectWithData:jSonData options:
                       NSJSONReadingMutableContainers error:&error];
            if (error==nil) {
                NSDictionary *mess=[result objectForKey:@"message"];
                NSDictionary *messContent=[mess valueForKeyPath:@"message"];
                NSDictionary *messDate=[mess valueForKeyPath:@"date"];
                NSDictionary *messID=[mess valueForKeyPath:@"ID"];
                NSDictionary    *messStatus=[mess valueForKey:@"status"];

                NSLog(@"%@ *** Message %@ \n Message Content: %@ \n Mesage ID: %@ \n Message Date: %@\n \nilhancetin MessageSatus: %@", result, mess, messContent, messID,messDate,messStatus);
                NSString*key1=[ result objectForKey:@"key" ];

                NSString *s1=[@"http://" stringByAppendingString:serverField.text];
                NSString *s2=[s1 stringByAppendingString:@"/ipad/button.php"];
                NSURL *url2=[NSURL URLWithString:[s2 stringByAppendingString:[@"?key=" stringByAppendingString:key1]]];
                NSLog(@"\n%@\n",url2 );
                NSData *data2=[NSData dataWithContentsOfURL:url2];
                id result2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];

                NSMutableArray *mesID = [NSMutableArray array];//saving meesages to NSMutableArray
                NSMutableArray *status = [NSMutableArray array];    


                // i logged here and it saves  the data, now i want to display my data in table view

`

I want to save the Notifications which come from server in my application and also make a User Interface to give users the ability of chosing which Notification(message) to read. In a scheduled method my client controls for changes inside the server and the communication is in JSON format. I have parsed it and can see the results in NSLog(@"....",..) too. I also control the status of message from the server, if the status equals to 1 i will save the message and add a node to TableView.. Now, can anyone help me about how to transmit datas in NSMutableArray both to NSUserDefaults and TableView? I can Share code or JSON representation too if you want..
It will be better if you could explain with some code.. Thanks

I decided to share some of my code,

as i have writen under the code too, i want to display NSMutableArray in UITableView

    `-(IBAction)Accept:(id)sender
    {   userName=[[NSString alloc] initWithString:userNameField.text ];
        [userNameField setText:userName];
        NSUserDefaults *userNameDef= [NSUserDefaults standardUserDefaults];
        [userNameDef setObject:userName forKey:@"userNameKey"];
        password =[[NSString alloc] initWithString:passwordField.text];
        [passwordField setText:password];
        NSUserDefaults *passDef=[NSUserDefaults standardUserDefaults];
        [passDef setObject:password forKey:@"passwordKey"];
        serverIP=[[NSString alloc] initWithString: serverField.text];
        [serverField setText:serverIP];
        NSUserDefaults *serverDef=[NSUserDefaults standardUserDefaults];
        [serverDef setObject:serverIP forKey:@"serverIPKey"];
        [userNameDef synchronize];
        [serverDef synchronize];
        [passDef synchronize];


    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                      message:@"Your User Informations are going to be sent to server. Do you accept?"
                                                     delegate:self
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:@"Cancel",  nil];
    [message show];
}



    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

        if([title isEqualToString:@"OK"])
        {
            if([userNameField.text isEqualToString:@""]|| [passwordField.text isEqualToString:@""] || [serverField.text length]<10) 
            {
                UIAlertView *message1 = [[UIAlertView alloc] initWithTitle:@"BNTPRO "
                                                                   message:@"Your User Informations are not defined properly!"
                                                                  delegate:nil
                                                         cancelButtonTitle:@"OK"
                                                         otherButtonTitles:  nil];

                [message1 show];


        [userNameField  resignFirstResponder];
            [passwordField resignFirstResponder];
            return;
        }
        //## GET code to here**
        NSString *str1=[@"?username=" stringByAppendingString:userNameField.text];
        NSString *str2=[@"&password=" stringByAppendingString:passwordField.text];
        NSString *str3=[str1 stringByAppendingString:str2];
        NSString *str4 =[@"http://" stringByAppendingString:serverField.text];


        NSURL *url=[NSURL URLWithString:[str4 stringByAppendingString:[@"/ipad/login.php" stringByAppendingString:str3]]];
        NSLog(@"%@\n",url);
        //get the url to jsondata
        NSData *jSonData=[NSData dataWithContentsOfURL:url];

        if (jSonData!=nil) {
            NSError *error=nil;
            id result=[NSJSONSerialization JSONObjectWithData:jSonData options:
                       NSJSONReadingMutableContainers error:&error];
            if (error==nil) {
                NSDictionary *mess=[result objectForKey:@"message"];
                NSDictionary *messContent=[mess valueForKeyPath:@"message"];
                NSDictionary *messDate=[mess valueForKeyPath:@"date"];
                NSDictionary *messID=[mess valueForKeyPath:@"ID"];
                NSDictionary    *messStatus=[mess valueForKey:@"status"];

                NSLog(@"%@ *** Message %@ \n Message Content: %@ \n Mesage ID: %@ \n Message Date: %@\n \nilhancetin MessageSatus: %@", result, mess, messContent, messID,messDate,messStatus);
                NSString*key1=[ result objectForKey:@"key" ];

                NSString *s1=[@"http://" stringByAppendingString:serverField.text];
                NSString *s2=[s1 stringByAppendingString:@"/ipad/button.php"];
                NSURL *url2=[NSURL URLWithString:[s2 stringByAppendingString:[@"?key=" stringByAppendingString:key1]]];
                NSLog(@"\n%@\n",url2 );
                NSData *data2=[NSData dataWithContentsOfURL:url2];
                id result2=[NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];

                NSMutableArray *mesID = [NSMutableArray array];//saving meesages to NSMutableArray
                NSMutableArray *status = [NSMutableArray array];    


                // i logged here and it saves  the data, now i want to display my data in table view

`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自在安然 2025-01-01 23:15:56

将其保存在 NSUserDefaults 中:

[[NSUserDefaults standardUserDefaults]setObject:yourArray forKey:@"theArray"];

从 NSUserDefaults 获取:

[[NSUserDefaults standardUserDefaults]objectForKey:@"theArray"];

将数组中的值设置为 UITableViewCell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"TheCell";
    UITableViewCell *_cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (_cell == nil) {
        _cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    _cell.textLabel.text = [yourArray objectAtIndex:indexPath.row];
    return _cell;
}

希望它有帮助

更新

目前附近没有 Mac,所以我的回答可能有点草率。

在你的头文件中,不要忘记添加 UITableViewDelegate 和 UITableViewDataSource,所以它看起来有点像这样:

@interface yourController : UIViewController <UITableViewDelegate, UITableViewDataSource, ... some others if you need it ...> {

然后在实现文件(.m)中,你可以开始输入

-tableview

,然后使用自动完成来获取你需要的方法。您很可能需要这 3 个:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath

根据应用程序的需求,您可能需要更多,但这 3 个应该存在。

有关 UITableView 的更多信息,请检查该链接: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

save it in NSUserDefaults:

[[NSUserDefaults standardUserDefaults]setObject:yourArray forKey:@"theArray"];

get it from NSUserDefaults:

[[NSUserDefaults standardUserDefaults]objectForKey:@"theArray"];

setting values from an array to UITableViewCell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"TheCell";
    UITableViewCell *_cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (_cell == nil) {
        _cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    _cell.textLabel.text = [yourArray objectAtIndex:indexPath.row];
    return _cell;
}

Hope it helps

update

don't have a Mac nearby at the moment, so my answer might be a bit sloppy.

In your header file don't forget to add UITableViewDelegate and UITableViewDataSource, so it will look somewhat like that:

@interface yourController : UIViewController <UITableViewDelegate, UITableViewDataSource, ... some others if you need it ...> {

then in the implementation file(.m) you can just start typing

-tableview

and then use the autocompletion to get the methods that you need. You will most probably need these 3:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath

depending on the needs of your app you might need more of them, but these 3 should be there.

For more info about UITableView please check that link: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文