当前位置:网站首页>OC -- Foundation -- dictionary
OC -- Foundation -- dictionary
2022-07-25 09:36:00 【Hills and valleys】
One 、 What is a dictionary
NSDictionary Used to save the array with mapping relationship .NSDictionary Two sets of values are stored in the set , One group is key, The other group is value. They can all be pointers of any type .
key Values are not allowed to be repeated .
key and value There is a one-to-one correspondence between them .
hold NSDictionary All in key Put together , They formed a NSSet aggregate (key Values have no order ,key and key Cannot be repeated between )
Two 、NSDictionary
1. establish
Class method dicotionary start , The example method takes init start
| dictionary: | Create one that does not contain any key-value Of NSDictionary |
|---|---|
| dictionaryWithContentdOfFile:(initWithContentsOfFile:) | Read the contents of the specified file , Initialize with the specified file contents NSD ictionary. This file is usually composed of NSDictionary Output generated |
| dictionaryWithDictionary:(initWithDictionary:) | Use existing NSDictionary Contains key-value To initialize the NSDictionary object |
| dictionaryWithObject:forKey: | Using a single key-value To create NSDictionary object |
| dictionaryWithobjects:forKeys:(initWithObjects:forKeys:) | Use two NSArray Assign separately key,value Collections can be created to contain multiple key-value Of NSDictionary |
| dictionaryWithObjectsAndKeys:(initWIthObjectsAndKeys:) | according to value1,key1,value2,key2… The format passed in multiple key-value Yes |
2. visit
- count: return NSDictionary It contains key-value logarithm
- allKeys: Return all contained key
- allKeysForObject: Returns the specified value Corresponding to all key
- allValues: Returns all... Contained in the dictionary value
- objectForKey: Used to get the specified in the dictionary key Of value
- objectForKeyedSubscript: It is allowed to obtain the specified by subscript key Corresponding value
- valueForKey: Get specified key It's the same as value
- keyEnumerator: Return to traverse all in the dictionary key Of NSEnumerator object
- objectEnumerator: Returns all... In the dictionary value Of NSEnumerator object
- enumerateKeysAndObjectsUsingBlock: Use the specified code block to iterate through all the in the collection key-value Yes
- enumerateKeysAndObjectsWithOptions:usingBlock: Use the specified code block to iterate through all the in the collection key-value Yes , It can be transmitted into a NSEnumerationOptions Parameters
- writeToFile:atomically: Write the contents of the dictionary to a file
user Class interface
#import<Foundation/Foundation.h>
@interface User:NSObject
@property(nonatomic,copy)NSString* name;
@property(nonatomic,copy)NSString* pass;
-(id)initWithName:(NSString*)aName
pass:(NSString*)aPass;
-(void)say:(NSString*)content;
@end
user The realization of the class
#import "06022.h"
#import<Foundation/Foundation.h>
@implementation User
-(id)initWithName:(NSString*)name
pass:(NSString*)pass{
if(self=[super init]){
self->_name=name;
self->_pass=pass;
}
return self;
}
-(void)say:(NSString*)content{
NSLog(@"%@ say :%@",self.name,content);
}
-(BOOL)isEqual:(id)other{
if(self==other){
return YES;
}
if([other class]==User.class){
User* target=(User*)other;
return [self.name isEqualToString:target.name]&&[self.pass isEqualToString:target.pass];
}
return NO;
}
-(NSString*)description{
return [NSString stringWithFormat:@"<User[name=%@,pass=%@]>",self.name,self.pass];
}
@end
Class interface
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSDictionary(print)
-(void)print;
@end
NS_ASSUME_NONNULL_END
The realization of the class
#import "0602.h"
@implementation NSDictionary (print)
-(void)print{
NSMutableString* result = [NSMutableString stringWithString:@"{"];
for(id key in self){
[result appendString:[key description]];
[result appendString:@"="];
[result appendString:[self[key] description]];
[result appendString:@","];
}
NSUInteger len = [result length];
[result deleteCharactersInRange:NSMakeRange(len-2,2)];
[result appendString:@"}"];
NSLog(@"%@",result);
}
@end
test :
#import<Foundation/Foundation.h>
#import"0602.h"
#import"06022.h"
int main(int argc,char* argv[]){
@autoreleasepool {
NSDictionary* dict = [NSDictionary
dictionaryWithObjectsAndKeys:
[[User alloc]initWithName:@"sun"
pass:@"123"],@"one",
[[User alloc]initWithName:@"bai"
pass:@"345"],@"two",
[[User alloc]initWithName:@"sun"
pass:@"123"],@"three",
[[User alloc]initWithName:@"tang"
pass:@"178"],@"four",
[[User alloc]initWithName:@"niu"
pass:@"155"],@"five",nil];
[dict print];
NSLog(@"dict contain %ld individual key-value Yes ",[dict count]);
NSLog(@"dict All of the key by :%@",[dict allKeys]);
NSLog(@"<User[name=sun,pass=123]> For all key by :%@",[dict allKeysForObject:[[User alloc]initWithName:@"sun" pass:@"123"]]);
NSEnumerator* en=[dict objectEnumerator];
id value;
while(value=[en nextObject]){
NSLog(@"%@",value);
}
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSLog(@"key The value of is :%@",key);
[value say:@" Nana "];
}];
}
}

3. Yes NSDictionary Of key Sort
keysSortedByValueUsingSelector: According to all return values key Sort , Sweet value This method of must return NSOrderedAscending,NSOrderedDescending,NSOrderedSame One of these three enumeration values .
keysSortedByValueUsingComparator: Use the specified code to traverse key-value Yes , And according to the results of the dictionary of all key sorted . The method must return NSOrderedAscending,NSOrderedDescending,NSOrderedSame One of these three enumeration values .
keysSortedByValueWithOptions:usingComparator: Use the specified code to traverse key-value Yes , And according to the results of the dictionary of all key sorted . It can be transmitted into a NSEnumerationOptions Parameters
The code of the interface part is the same as the above , Here is the test code
#import<Foundation/Foundation.h>
#import"0602.h"
#import"06022.h"
int main(int argc,char* argv[]){
@autoreleasepool {
NSDictionary* dict = @{
@"one":@"nana",
@"two":@"nuonuo",
@"three":@"magic",
@"four":@"hailuo"};
[dict print];
NSArray* keyArr1 = [dict keysSortedByValueUsingSelector:@selector(compare:)];
NSLog(@"%@",keyArr1);
NSArray* keyArr2 = [dict keysSortedByValueUsingComparator:^(id value1,id value2) {
if([value1 length]>[value2 length]){
return NSOrderedDescending;
}if([value1 length]<[value2 length]){
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSLog(@"%@",keyArr2);
}
}
give the result as follows :
- First call value Of compare: Methods the sorting , String comparison size is directly based on character encoding
- Call the code block for all of the dictionary for the second time value Compare the size ,value The longer the corresponding string , The system thinks that value The bigger it is .
4. Yes NSDictionary Of key Filter
NSDictionary Provide for the right to NSDictionary All of the key filtering , After completion, it will meet the return filter conditions key form NSSet.
The interface part and implementation part are the same as above , Here is the test code :
#import<Foundation/Foundation.h>
#import"0602.h"
#import"06022.h"
int main(int argc,char* argv[]){
@autoreleasepool {
NSDictionary* dict = @{
@"nuonuo":[NSNumber numberWithInt:89],
@"hailuo":[NSNumber numberWithInt:69],
@"nana":[NSNumber numberWithInt:75],
@"magic":[NSNumber numberWithInt:109]};
[dict print];
NSSet* keySet = [dict keysOfEntriesPassingTest:^(id key,id value,BOOL* stop){
return (BOOL)([value intValue]>80);
}];
NSLog(@"%@",keySet);
}
}
give the result as follows :
3、 ... and 、 Custom type as key
Requirements that custom types need to meet :
Correctly rewritten isEqual: and hash Method
Realized copyWithZone: Method , It is best to return an immutable copy of the object . It's for security reasons , When the program bar more key-value After the value is passed into the dictionary , For a dictionary ,key What is critical , Dictionaries need to be based on key To visit value.value It is equivalent to the index of dictionary elements . If key Variable value , And the program can modify the dictionary through other variables key, It may cause the index of the dictionary to be destroyed , The integrity of the dictionary is destroyed
Supplement to class implementation
- (id) copyWithZone: (NSZone*) zone {
NSLog(@"start");
FKUser* newUser = [[[self class] allocWithZone:zone] init];
newUser->name = name;
newUser->pass = pass;
return newUser;
}
test :
#import<Foundation/Foundation.h>
#import"0602.h"
#import"06022.h"
int main(int argc,char* argv[]){
@autoreleasepool {
User* u1=[[User alloc]initWithName:@"bai" pass:@"345"];
NSDictionary* dict = @{
[[User alloc]initWithName:@"sun" pass:@"123"]:@"one",u1:@"two",
[[User alloc]initWithName:@"sun" pass:@"123"]:@"three",
[[User alloc]initWithName:@"tang" pass:@"178"]:@"four",
[[User alloc]initWithName:@"niu" pass:@"155"]:@"five"};
u1.pass = nil;
[dict print];
}
}
Four 、NSMUtableDictionary
NSMUtableDictionary Inherited NSDictionary, Representing one key-value Variable NSDictionary aggregate .
#import <Foundation/Foundation.h>
#import "NSDictionary+print.h"
int main(int argc, char* argv[]) {
@autoreleasepool {
NSMutableDictionary* dict = [NSMutableDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:89], @" Hey ", nil];
dict[@" Hey "] = [NSNumber numberWithInt:99];
[dict print];
NSLog(@"again");
dict[@" Nana "] = [NSNumber numberWithInt:69];
[dict print];
NSDictionary* dict2 = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:79], @" magical ",
[NSNumber numberWithInt:89], @"hai", nil];
[dict addEntriesFromDictionary:dict2];
[dict print];
[dict removeObjectForKey:@" Hey "];
[dict print];
}
return 0;
}

边栏推荐
猜你喜欢
随机推荐
How to write Android switching interface with kotlin
Prim 最小生成树(图解)
Excl batch import data, background public parsing method
【代码源】每日一题 树
Redis database foundation
Go foundation 2
浏览器访问swagger失败,显示错误ERR_UNSAFE_PORT
@3-1 CCF 2020-09-1 称检测点查询
数据查询语言(DQL)
【代码源】每日一题 算的我头都大啦
关于学生管理系统(注册,登录,学生端)
Understand why we should rewrite the equals method and hashcode method at the same time + example analysis
cell的定义
What are stand-alone, cluster and distributed?
Idea practical tips --- now change pom.xml (red) to pom.xml (blue)
Swagger2 shows that there is a problem with the get interface, which can be solved with annotations
[GYCTF2020]Node Game
laravel 调用第三方 发送邮件 (php)
Idea hot deployment
【cf】Round 128 C. Binary String




![[GYCTF2020]Ez_Express](/img/ce/02b90708f215715bb53cacfd4c21f0.png)





