我阅读了所有关于新的Objective-C文字,并使用
Xcode转换我的旧代码,但索引代码没有改变.我手动改变它,但它不会编译.我看到一篇帖子说我们要等到iOS 6,但我现在要索引!
有什么解决方案吗?
解决方法
好吧,有办法做到这一点!将索引方法作为类别添加到NSArray和NSDictionary中,您可以获得您希望它的大多数类的功能.您可以阅读ObjectiveC文字
here.感谢James Webster的@YES和@NO解决方案,您现在也可以在项目中正确使用它们!
(the technique)
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
来自:格雷格帕克
至: …
主题:Re:如何让iOS 5上的Obj-C集合下载工作?
…
As an experiment I added the category @interface for these methods,but not the @implementation — the app still ran fine (at least in the 5.1 simulator)
编译器发出相同的调用.神奇之处在于越来越不准确地命名为libarclite(“它不仅仅适用于ARC Anymore™”),它在运行时添加了下标方法的实现(如果它们尚不存在).
IIRC有一些可下标的类,libarclite不升级(可能是NSOrderedSet?)所以你仍需要对旧的部署目标进行彻底测试.