[英]Objective-C Category Question
我通過為NSString
類創建新類別來創建自定義排序。 下面是我的代碼。
@implementation NSString (Support)
- (NSComparisonResult)sortByPoint:(NSString *)otherString {
int first = [self calculateWordValue:self];
int second = [self calculateWordValue:otherString];
if (first > second) {
return NSOrderedAscending;
}
else if (first < second) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
- (int)calculateWordValue:(NSString *)word {
int totalValue = 0;
NSString *pointPath = [[NSBundle mainBundle] pathForResource:@"pointvalues"ofType:@"plist"];
NSDictionary *pointDictionary = [[NSDictionary alloc] initWithContentsOfFile:pointPath];
for (int index = 0; index < [word length]; index++) {
char currentChar = [word characterAtIndex:index];
NSString *individual = [[NSString alloc] initWithFormat:@"%c",currentChar];
individual = [individual uppercaseString];
NSArray *numbersForKey = [pointDictionary objectForKey:individual];
NSNumber *num = [numbersForKey objectAtIndex:0];
totalValue += [num intValue];
// cleanup
individual = nil;
numbersForKey = nil;
num = nil;
}
return totalValue;
}
@end
我的問題是我是否創建一個點字典來基於plist確定與字母表中每個字符關聯的點值。 然后在我的視圖控制器中,
NSArray *sorted = [words sortedArrayUsingSelector:@selector(sortByPoint:)];
根據它們的點值對我的單詞表進行排序。 但是,每次調用-sortByPoint:
方法時都創建一個新字典效率極低。 有沒有一種方法可以預先創建pointDictionary並將其用於-calculateWordValue:
中的每個后續調用?
這是static關鍵字的工作。 如果您這樣做:
static NSDictionary *pointDictionary = nil
if (pointDictionary==nil) {
NSString *pointPath = [[NSBundle mainBundle] pathForResource:@"pointvalues" ofType:@"plist"];
pointDictionary = [[NSDictionary alloc] initWithContentsOfFile:pointPath];
}
pointDictionary
將在應用程序的生命周期內保持pointDictionary
。
另一種優化是通過針對每個單詞使用此分數來構建分數緩存:
[dict setObject:[NSNumber numberWithInt:[word calculateWordValue:word]] forKey:word];
然后使用keysSortedByValueUsingSelector:
方法提取單詞列表(請注意,選擇器應該進行比較:,因為被比較的對象是NSNumbers)。
最后,方法中的單詞參數是多余的。 改用self:
-(int)calculateWordValue {
...
for (int index = 0; index < [self length]; index++)
{
char currentChar = [self characterAtIndex:index];
...
}
...
}
更改您的sortByPoint:(NSString *) otherString
方法,以將字典作為參數,並將其傳遞給您預先創建的字典。
sortByPoint:(NSString *)otherString withDictionary:(NSDictionary *)pointDictionary
編輯:由於在sortedArrayWithSelector中的使用而無法使用。 道歉。 取而代之的是,最好為您的點字典創建一個包裝類,使其成為單例,然后您在每次運行sort函數時都獲得對它的引用。
在calculateWordValue
:
NSDictionary *pointDictionary = [[DictWrapper sharedInstance] dictionary];
DictWrapper
具有NSDictionary作為屬性,並且具有類方法sharedInstance
(以返回單例。您必須先設置該字典並對其進行初始化,然后才能進行首次排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.