Objective C - 在创建字符串数组时应用程序崩溃,我疯了吗?

Jul*_*ien 3 iphone cocoa cocoa-touch objective-c

如果我尝试使用这个简单的代码:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    // Add the tab bar controller's current view as a subview of the window
    [window addSubview:tabBarController.view];

    NSString *stringMer = [NSString stringWithFormat:@"OK COOL"] ;
    NSString *stringMer2 = [NSString stringWithFormat:@"OK COOL"];

    NSArray *truc = [NSArray arrayWithObjects:stringMer,stringMer2];
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序崩溃("无法读取未知的加载命令0x22"或只是常规崩溃)... applicationDidFinishLaunching来自我的FooAppDelegate,我没有更多的代码,这是正常的吗?

Ale*_*ski 37

传递给arrayWithObjects:方法的参数列表必须是nil-terminated:

NSArray *truc = [NSArray arrayWithObjects:stringMer,stringMer2, nil];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您使用`-Wformat`编译,GCC将警告您,如果您忘记了`nil` - 请查看[GCC的`sentinel`函数属性] [sentinel]和标题`<Foundation/NSObjCRuntime.h>`for`NS_REQUIRES_NIL_TERMINATION `.您还可以通过指定`-Werror'使构建失败以进行警告.[sentinel]:http://developer.apple.com/mac/library/documentation/DeveloperTools/gcc-4.0.1/gcc/Function-Attributes.html"功能属性" (5认同)

NSR*_*der 9

不要使用+ stringWithFormat:除非你实际上有一个需要解析的格式字符串.