小编sic*_*ckp的帖子

静态NSString用法与内联NSString常量

在Objective-C中,我的理解是指令@"foo"定义了一个常量NSString.如果我在多个地方使用@"foo",则引用相同的不可变NSString对象.

为什么我经常看到这段代码片段(例如在UITableViewCell重用中):

static NSString *CellId = @"CellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:CellId];
Run Code Online (Sandbox Code Playgroud)

而不仅仅是:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId"];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"CellId"];
Run Code Online (Sandbox Code Playgroud)

我假设它是为了保护我不会在编译器无法捕获的标识符名称中输入错误.但如果是这样,我不能只是:

#define kCellId @"CellId"
Run Code Online (Sandbox Code Playgroud)

并避免静态NSString*位?或者我错过了什么?

objective-c nsstring ios

42
推荐指数
3
解决办法
2万
查看次数

NS在线程中使用

我正试图NSAssert在我的iPhone应用程序中使用,以便在发生意外情况时,应用程序失败,并在崩溃日志中崩溃并显示有意义的消息.

如果失败NSAssert在主线程上,这可以正常工作,因为NSInternalInconsistencyException默认情况下它会被捕获并且会停止执行.但我也在后台线程中处理,在这种情况下,NSAssert只是中止线程,但编程继续运行.

我目前的解决方案是在主线程中捕获并重新抛出异常(在本例中为NSOperation's main方法):

- (void)main {
    @try {
        int x = 14;
        ...
        NSAssert1(x > 20, @"x should be greater than 20, was %d", x);
        ...
    }
    @catch (NSException *e) {
        [e performSelectorOnMainThread:@selector(raise) withObject:nil waitUntilDone:YES];
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?也许使用自定义NSAssertionHandler?

我知道我可以使用assert带有静态注释的C :

assert(x > 20 && "x should be greater than 20");
Run Code Online (Sandbox Code Playgroud)

但这不允许我展示实际的失败价值x是什么.

iphone assert objective-c nsoperation nsthread

5
推荐指数
1
解决办法
3625
查看次数

如何在 nginx 中不返回错误/error_page 的正文/内容?

如果找不到文件或禁止文件等 - 我真的很想只返回 HTTP 状态代码而不返回正文内容。就像是:

error_page 403 404 body="";
Run Code Online (Sandbox Code Playgroud)

当前(2015 年)的最佳实践是什么?

nginx http-status-code-403 http-status-code-404

3
推荐指数
1
解决办法
4779
查看次数