[英]Is there any way to get the neat Objective-C literal indexing feature in Xcode 4.4?
我阅读了所有关于新的Objective-C文字,并使用Xcode转换我的旧代码,但索引代码没有改变。 我手动改变它,但它不会编译。 我看到一篇帖子说我们要等到iOS 6,但我现在要索引!
有什么解决方案吗?
好吧,有办法做到这一点! 将索引方法作为类别添加到NSArray和NSDictionary中,您可以获得您希望它的大多数类的功能。 您可以在此处阅读ObjectiveC文字。 感谢James Webster为@YES和@NO提供的解决方案,您现在也可以在项目中正确使用它们! (技术)
1)创建接口文件
// NSArray+Indexing.h
#if !defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
@interface NSArray (Indexing)
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
@end
@interface NSMutableArray (Indexing)
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
@end
// NSDictionary+Indexing.h
@interface NSDictionary (Indexing)
- (id)objectForKeyedSubscript:(id)key;
@end
@interface NSMutableDictionary (Indexing)
- (void)setObject:(id)obj forKeyedSubscript:(id)key;
@end
#endif
2)创建实施文件//在执行此操作之前参见下面的编辑 - 您可以跳过此步骤
// NSArray+Indexing.m
#if !defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
#import "NSArray+Indexing.h"
@implementation NSArray (Indexing)
- (id)objectAtIndexedSubscript:(NSUInteger)idx
{
return [self objectAtIndex:idx];
}
@end
@implementation NSMutableArray (Indexing)
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx
{
[self replaceObjectAtIndex:idx withObject:obj];
}
@end
// NSMutableDictionary+Indexing.m
@implementation NSDictionary (Indexing)
- (id)objectForKeyedSubscript:(id)key
{
return [self objectForKey:key];
}
@end
@implementation NSMutableDictionary (Indexing)
- (void)setObject:(id)obj forKeyedSubscript:(id)key
{
[self setObject:obj forKey:key];
}
@end
#endif
3)将接口文件添加到pch文件以供全局使用,或根据需要将它们添加到.m文件中
// Add to PCH file
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
...
#if !defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
// New Indexing
#import "NSDictionary+Indexing.h"
#import "NSArray+Indexing.h"
// Provided by James Webster on StackOverFlow
#if __has_feature(objc_bool)
#undef YES
#undef NO
#define YES __objc_yes
#define NO __objc_no
#endif
#endif
#endif
#endif
4)重建,然后添加以下文件以验证它是否全部有效
// Test Example
{
NSMutableArray *a = [NSMutableArray arrayWithArray:@[ @"a", @"b", @"c" ]];
NSLog(@"%@", a[1]);
a[1] = @"foo";
NSLog(@"a: %@", a);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{ @"key" : @"object" }];
NSLog(@"%@", dict[@"key"]);
dict[@"key"] = @"New Object";
dict[@"newKey"] = @"WOW a new object";
NSLog(@"dict: %@", dict);
NSLog(@" %@ %@", @YES, @NO );
}
编辑:嗯,根据一位关键的llvm / clang Apple工程师的说法,有一个库已经与实现相关联,所以你只需要接口文件:
日期:星期一,2012年8月20日15:16:43 -0700来自:Greg Parker To:...主题:Re:如何在iOS 5上制作Obj-C集合下载工作? ...
作为一个实验,我为这些方法添加了@interface类别,但没有添加@implementation - 应用程序仍然正常运行(至少在5.1模拟器中)
编译器发出相同的调用。 神奇之处在于越来越不准确地命名为libarclite(“它不仅仅适用于ARC Anymore™”),它在运行时添加了下标方法的实现(如果它们尚不存在)。
IIRC有一些可下标的类,libarclite不升级(可能是NSOrderedSet?)所以你仍需要对旧的部署目标进行彻底的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.