簡體   English   中英

添加新元素后無法重新加載tableviewcontroller

[英]Can't get a tableviewcontroller to reload after adding a new element

所以我已經嘗試了一段時間,這讓我很沮喪,但是這里是我正在嘗試做的簡短摘要。 我有一個LocationTableViewController,在右上角有一個加號按鈕,用於向表格視圖添加新位置。 發生這種情況時,我輸入LocationEditViewController,在其中輸入要添加的位置的名稱。 添加文本並單擊“保存位置”按鈕后,我希望代碼將我帶回到LocationTableViewController,然后在表中看到新添加的位置。 下面發布的是兩個視圖控制器的代碼。 希望你們能幫助我,謝謝你!

#import <UIKit/UIKit.h>
#import "Location.h"
#import "User.h"

@interface LocationEditViewController : UIViewController <UITextFieldDelegate>

@property (strong, nonatomic) Location *location;
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) UITextField *locationNameField;

- (void)saveLocation:(id) sender;

@end


#import "LocationEditViewController.h"

@interface LocationEditViewController ()

@end

@implementation LocationEditViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"Edit";
        self.location = [[Location alloc] init];
        self.user = [[User alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    UILabel *locationLabel = [[UILabel alloc] init];
    locationLabel.frame = CGRectMake(20,15,50,30);
    locationLabel.text = @"Name:";
    [self.view addSubview:locationLabel];

    self.locationNameField = [[UITextField alloc] init];
    self.locationNameField.frame = CGRectMake(15,50,290,30);
    self.locationNameField.borderStyle = UITextBorderStyleBezel;
    self.locationNameField.keyboardType = UIKeyboardTypeDefault;
    self.locationNameField.delegate = self;
    [self.view addSubview:self.locationNameField];

    UIButton *saveLocationButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    saveLocationButton.frame = CGRectMake(15,400,290,50);
    [saveLocationButton setTitle:@"Save Location" forState:UIControlStateNormal];
    [saveLocationButton addTarget:self action:@selector(saveLocation:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveLocationButton];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)saveLocation:(id)sender {
    self.location.name = self.locationNameField.text;

    NSMutableArray *tempArray = [[NSMutableArray alloc] initWithArray:self.user.createdLocations];
    [tempArray addObject:self.location];
    self.user.createdLocations = [[NSArray alloc] initWithArray:tempArray];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Added"
                                                    message:@"This location is now accessable in the locations tab"
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    [alert show];

    [self.tabBarController.tabBar.items[1] setBadgeValue:[NSString stringWithFormat:@"%i",self.user.createdLocations.count]];

    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"somethingAddedNotification" object:nil];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

這是LocationTableViewController代碼:

#import <UIKit/UIKit.h>
#import "User.h"

@interface LocationTableViewController : UITableViewController

@property (strong, nonatomic) NSArray *locations;
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) id _observer;

- (void) addLocationPressed;

@end



#import "LocationTableViewController.h"
#import "LocationEditViewController.h"
#import "LocationViewController.h"

@interface LocationTableViewController ()

@end

@implementation LocationTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = @"Locations";
        self.user = [[User alloc] init];
        UIBarButtonItem *addLocationButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addLocationPressed)];
        self.navigationItem.rightBarButtonItem = addLocationButton;

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Location *loc = [[Location alloc] init];
    //self.user.createdLocations = @[loc];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void) addLocationPressed
{
    LocationEditViewController *locationEditVC = [[LocationEditViewController alloc] init];
    [self presentViewController:locationEditVC animated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.user.createdLocations.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }
    cell.textLabel.text = [self.user.createdLocations[indexPath.row] name];
    NSLog(@"%@", [self.user.createdLocations[indexPath.row] name]);

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    LocationViewController *locationVC = [[LocationViewController alloc] init];
    locationVC.location = self.user.createdLocations[indexPath.row];

    [self.navigationController pushViewController:locationVC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    __observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"somethingAddedNotification"
                                                                  object:nil
                                                                   queue:nil
                                                              usingBlock:^(NSNotification *notification)
    {
        [self.tableView reloadData];
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:__observer];
}

有關其他信息,這里是我要獲取數組的用戶類

#import <Foundation/Foundation.h>
#import "Location.h"

@interface User : NSObject

@property (strong, nonatomic) Location *profilePhoto;
@property (strong, nonatomic) NSString *location;
@property (strong, nonatomic) NSArray *createdLocations;


-(id) initWithTitle: (Location *) aLoc
             detail: (NSString *) aDet
           filename: (NSArray *) aLocList;

//-(id)initWithJSON;
//+(NSString *)getPathToArchive;

//+(User *)getUser;
//+(void)saveUser:(User *)aUser;

@end

#import "User.h"
#import "Location.h"

@implementation User

- (id)init;
{
    self = [self initWithTitle: [[Location alloc] init]
                        detail: @"Temp"
                      filename: [[NSArray alloc] init]];
    return self;
}

-(id) initWithTitle: (Location *) aLoc
             detail: (NSString *) aDet
           filename: (NSArray *) aLocList
{
    self = [super init];
    if (self) {
        self.profilePhoto = aLoc;
        self.location = aDet;
        self.createdLocations = aLocList;
    }
    return self;

}

@end

以及位置類(如果需要)

#import <Foundation/Foundation.h>

@interface Location : NSObject

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *detail;
@property (strong, nonatomic) NSString *filename;
@property (strong, nonatomic) NSString *thumbnail;

-(id) initWithTitle: (NSString *) aTitle
             detail: (NSString *) aDetail
           filename: (NSString *) aFilename
          thumbnail: (NSString *) aThumbnail;

@end

#import "Location.h"

@implementation Location

-(id)init
{
    self = [self initWithTitle:@"Title"
                        detail:@"Detail"
                      filename:@"placeholder.jpg"
                     thumbnail:@"placeholder.jpg"];
    return self;
}

-(id)initWithTitle:(NSString *)aTitle
            detail:(NSString *)aDetail
          filename:(NSString *)aFilename
         thumbnail:(NSString *)aThumbnail
{
    self = [super init];
    if (self) {
        self.name = aTitle;
        self.detail = aDetail;
        self.filename = aFilename;
        self.thumbnail = aThumbnail;
    }
    return self;
}

@end

希望你們能幫助我! 再次感謝!!!

您是否在...上設置了斷點?

[self.tableView reloadData];

...在您的觀察者區? 它會受到打擊嗎? 另外,Drew Crawford對正在使用的API保持警惕( http://sealedabstract.com/code/nsnotificationcenter-with-blocks-considered-harmful/ )。

就像評論所說,這絕對是一個問題,實際上可能是根本原因。 您必須在塊內使用__weak引用,否則NSNotificationCenter擁有對self的強引用,而self擁有對NSNotificationCenter的強引用,並且您有一個保留周期。

- (void)viewWillAppear:(BOOL)animated {

    __weak LocationTableViewController *weakSelf = self;

    __observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"somethingAddedNotification"
                                                                  object:nil
                                                                   queue:nil
                                                              usingBlock:^(NSNotification *notification)
    {
        [weakSelf.tableView reloadData];
    }];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM