【问题标题】:NSObject does not give data UIViewControllerNSObject 不给数据 UIViewController
【发布时间】:2016-08-11 15:46:15
【问题描述】:

问题描述如下:

  1. NSObject中包含的UIViewController链接函数中包含的函数
  2. NSObject 将值返回给 UIViewController 中包含的另一个函数
  3. 当一个函数引用到 UIViewController 时,它不会更新 UILabel

在 UIViewController 中找到 UILabel

NSObject 类:

-(void)getCategoryId:(NSString *)categoryid {
    categoryMap *catMap = [[categoryMap alloc] init];
    [catMap getCategoryId:categoryid];
    catMap.nePOI = categoryid;
}

UIViewController:

-(void)getCategoryId:(NSString *)categoryid {
    self.label.text = categoryid;
}

【问题讨论】:

  • @TejaNandamuri 我写了一个问题的例子。默认情况下,有一些准则。我呼吁在当地正常运作。
  • 当值改变时可以使用Delegate(协议)传递数据。此外,NSNotificationCenter 也是一个不错的选择。

标签: ios objective-c uiviewcontroller iboutlet


【解决方案1】:

您正在创建一个新的 categoryMap 视图控制器对象,并且您正在更新它的标签,而不是当前显示的 categoryMap 视图控制器中的标签。 为了实现你想要的,“NSObject”实例必须有一个指向实际显示在屏幕上的 ViewController 的引用(属性)。

-(void)getCategoryId:(NSString *)categoryid {
    // View controller is created
    categoryMap *catMap = [[categoryMap alloc] init];

     // label updated
    [catMap getCategoryId:categoryid];
    catMap.nePOI = categoryid;

    // End of the method, View controller is destroyed
    // See the problem here??? You are not updated the good viewController...
}

虽然这不是推荐的方式。您的 viewController 应该询问对象要显示什么,而不是相反。但是,在您的情况下,您可以通过通知解决此问题。将对象类中getCategoryId:的实现替换为

[[NSNotificationCenter defaultCenter] postNotificationWithName:@"categorySelected" object:categoryId];

并在您的视图控制器中订阅它viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCategoryId:) name:@"categorySelected" object:nil];

然后将视图控制器的 getCategoryId: 方法替换为:

-(void)getCategoryId:(NSNotification *)notif {
    self.label.text = (NSString *)(notif.object);
}

应该可以... ;)

为了更好地理解 ViewController 原理背后的架构,请参考 Apple MVC 文档:https://developer.apple.com/library/mac/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 2020-10-23
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多