objective-c - iOS ivar alloc/init 分配内存地址给另一个ivar

标签 objective-c ios xcode memory-management automatic-ref-counting

我已经在我的一个 View Controller 的界面中声明了两个 NSMutableArray,如您在下面的代码中所见。但是,在综合属性之后,我尝试在 viewDidLoad 中初始化我的类的 ivars。如果我在调试器中跨过这个过程,我会看到它正在用一个 ivar 抵消内存分配,如果这有意义的话。因此,例如,当我初始化第一个 NSMutableArray 时,我可以看到内存地址被分配给另一个 NSMutableArray ivar。代码应该初始化的 NSMutableArray 仍然是一个空内存地址。内存分配中的这个奇怪的“偏移量”也尝试初始化第二个 NSMutableArray ...它在我的 DataHelper ivar 的内存位置中初始化。这会导致稍后在代码中抛出错误,例如:

-[DataHelper count]: unrecognized selector sent to instance

它期望引用内存中的 NSMutableArray,但它指向的是 DataHelper 内存地址。有没有人经历过这样的事情?我使用的是 ARC、最新版本的 Xcode 和 iOS 5.1。

MyViewController.h

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

@interface MyViewController : UIViewController
{
    DataHelper *dataHelper;
    NSMutableArray *recentPosts;
    NSMutableArray *popularPosts;
}

@property (nonatomic, strong) DataHelper *dataHelper;
@property (nonatomic, strong) NSMutableArray *recentPosts;
@property (nonatomic, strong) NSMutableArray *popularPosts;

@end

MyViewController.m 中的 viewDidLoad

@implementation MyViewController

@synthesize dataHelper, recentPosts, popularPosts;

- (void)viewDidLoad
{
    [super viewDidLoad];

    recentPosts = [[NSMutableArray alloc] init];
    popularPosts = [[NSMutableArray alloc] init];
    dataHelper = [[DataHelper alloc] init];

    // I've also tried initializing the ivars as above, with "self." prefix

    recentPosts = [dataHelper getSuggestionsByMostRecent:1];
    popularPosts = [dataHelper getSuggestionsByPopular:1];
}

最佳答案

ARC 希望您的方法名称遵循 cocoa(-touch) naming conventions . 而 getSuggestionsByMostRecent 违反了该约定。特别是这个:

Use “get” only for methods that return objects and values indirectly. You should use this form for methods only when multiple items need to be returned.

那将是一个有效的获取方法(虽然不是一个好方法):- (void)getString:(NSString **)str

如果不使用正确的命名方案,ARC 不知道在哪里添加保留或释放。

尝试将您的方法重命名为类似suggestionsSortedByMostRecent: 的名称。没有得到。

关于objective-c - iOS ivar alloc/init 分配内存地址给另一个ivar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682989/

相关文章:

objective-c - Objective-C 类别和扩展的细节

ios - 如何为ios7 3.5英寸和4英寸屏幕设置UITableview的背景图片

ios - 多个 NSManagedObjectContexts 问题

ios - 应用程序崩溃后收到来电 twilio

ios - 为什么我在左侧边栏的 xcode 中看不到我工作区中的所有文件?

iOS:如何从一个 UIViewController 切换到另一个,包括在 SWRevealViewController

ios - NSNotification 与 UITextFieldDelegate

iphone - 如何将相同的 UIButton 添加到 iphone 中所有 View Controller 的导航栏?

ios - NSTextContainer exclusionPaths 卡住应用程序并在 iOS 7.1 上使用 99% 的 CPU - 解决方法?

ios - 归档因 XCode 10、Cocoapods 和新构建系统而失败