当前位置:网站首页>[OC foundation framework] - [set array]
[OC foundation framework] - [set array]
2022-07-06 08:58:00 【About Xiaosi】
List of articles
- OC Overview of the collection
- Array NSArray And variable arrays NSMutableArray
- establish NSArray Several kinds of methods
- see NSArray Several operations of array
- Enumeration traversal NSArray Collection elements
- Variable array (NSMutableArray)
- NSArray Of KVC and KVO( This article does not explain , I haven't learned relevant knowledge about monitoring for the time being )
OC Overview of the collection
- OC The collection class of can be used to store multiple objects with unequal number and realize common data structures
- OC The set can be roughly divided into NSArray,NSSet, NSDictionary Three
- NSArray, An ordered and repeatable set
- ,NSSet An unordered and unrepeatable set
- ,NSDictionary Set with mapping relationship
Array NSArray And variable arrays NSMutableArray
NSArray Class methods and instance methods are provided to create NSArray, The parameters passed in by the two methods are basically similar
Class method array start The example method takes init start
establish NSArray Several kinds of methods
array: Create an empty... That does not contain any elements NSArray.
array WithContentsOfFile:/nit With ContentsOfFile:: Read the contents of the file to create NSArray
array WithObject:/initwithObject: Create a that contains only the specified elements - NSArray.
array WithObjects:/initWithObjecti: Create a file that contains the specified Enter into An element of NSArray.
besides , You can also create NSArray object . NSArray *array = @[,]
Create code
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray* array = [NSArray arrayWithObjects:@"3g",@"Android", @"Ajax", @"XML", @"Swift", nil];
NSLog(@" First element %@", array[0]);
NSLog(@" The last element %@", [array lastObject]);
// Get index from 2 Element start of , And the set composed of the following three elements
NSArray *arr1 = [array objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(2, 3)]];
NSLog(@" %@", arr1);
// Get the position of element Russia in the set
NSLog(@" Elements Ajax The position is : %ld", [array indexOfObject:@"Ajax"]);
// Gets the position of the element in the specified range of the collection
NSLog(@" stay 2-5 Range Android The position is %ld", [array indexOfObject:@"Android"inRange:NSMakeRange(2, 3)]);
// aggregate [16654:2344761] stay 2-5 Range Android The position is 9223372036854775807
// Can't find
// In fact, this is also a constant NSNotFound Value
// Additional elements
// String like NSArray It doesn't change in itself , Return the new NSArray Assign a value to array
array = [array arrayByAddingObject:@" magical iOS"];
// Append all the elements of two new arrays to the end of the array
// String like NSArray It doesn't change in itself , Return the new NSArray Assign a value to array
array = [array arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:@" Magical non saving room 222", @"s Magical complication ", @" Magical me ", nil]];
for (int i= 0; i < array.count; i++) {
// NSLog(@"%@-", [array objectAtIndex:i]);
NSLog(@"%@", array[i]);
// To study the c Familiar with the second array usage !
}
// Write array collection to file
[arr1 writeToFile:@"myFile.txt" atomically:YES];
}
return 0;
}
Operation details
1) Traversing set elements
objectAtIndex:index perhaps array[i]
The latter is recommended
2) towards NSArray Add elements after
arrayByAddingObject:-- Append a single element
arrayWithObjexts: Method appends all elements of another array to the end of the array
3) It is worth mentioning that We NSArray Array is immutable, so the way to change the value inside the array is to open up a new space and point the array pointer to the new array instead of operating in the old array
see NSArray Several operations of array
- Query collection elements in NSArray Index in .
- Take out... According to the index value NSArray The elements in the collection .
- Call the method as a whole on the collection element .
- Yes NSArray Set to sort .
NSArray How to determine whether a set contains a formulation element
- There is only one standard : This is what we learned before isEqual Method when the comparison returns YES, It can be considered that NSArray Set contains
This element , You don't need two elements to be the same element ;
NSArray Comparison mechanism
rewrite isEqual
- To verify the comparison mechanism Create a FKUser object
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FKUser : NSObject
@property (nonatomic, copy) NSString* name;
@property (nonatomic, copy) NSString* pass;
- (id) initWithName : (NSString*) aName pass:(NSString*) aPass;
- (void) say:(NSString*) content;
@end
NS_ASSUME_NONNULL_END
#import "FKUser.h"
@implementation FKUser
- (id) initWithName:(NSString *) name pass:(NSString *) pass {
if (self = [super init]) {
self->_name = name;
self->_pass = pass;
}
return self;
}
- (void) say: (NSString*) content {
NSLog(@" %@ Shouted loudly in an invincible voice :%@", self.name, content);
}
// Rewrite the comparison method , The comparison standard is if two FKUSer Of name pass equal They can be considered equal
- (BOOL) isEqual:(id) other {
if (self == other) {
return YES;
} else if ([other class] == FKUser .class) {
FKUser* target = (FKUser*)other;
return [self.name isEqualToString:target.name] &&[self.pass isEqualToString:target.pass];
}
return NO;
}
@end
- Note that we have customized isEqual Standards for , Rewrite the comparison method , The comparison standard is if two FKUSer Of name pass equal They can be considered equal
test isEuqal
#import <Foundation/Foundation.h>
#import "FKUser.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// establish NSArray object
NSArray* array = @[
[[FKUser alloc] initWithName:@"sun" pass:@"123"],
[[FKUser alloc] initWithName:@"bai" pass:@"345"],
[[FKUser alloc] initWithName:@"zhu" pass:@"654"],
[[FKUser alloc] initWithName:@"tang" pass:@"178"],
[[FKUser alloc] initWithName:@"niu" pass:@"155"]];
// Find the specified new FKUser The index of the object in the collection
FKUser* newUser = [[FKUser alloc] initWithName:@"zhu" pass:@"654"];
NSUInteger pos = [array indexOfObject:newUser];
NSLog(@" Find the newUser The location of the for %ld", pos);
}
return 0;
}
- Our test example is to create a FKUser object Although this object is not one of the objects in our array But it has the same properties as an object in the array, which satisfies the rewritten isEqual The method can
Yes NSArray Sort
NSArray Three sorts are provided
- sortedArrayUsingFunction:context:: Use the sort function to sort the collection of elements , The function must return NSOrderedDescending、NSOrderedAscending、NSorderedSame These enumeration values , Used to represent the size of collection elements . This method returns a sorted new NSArray object .
- sortedArrayUsingSelector:: Use the method of the collection element itself to sort the collection elements , The function must return NSOrderedDescending、NSOrderedAscending、NSorderedSame These enumeration values , Used to represent the size of collection elements . This method returns a sorted new NSArray object .
- sortedArrayUsingComparator:: Use code blocks to sort collection elements , The function must return NSOrderedDescending、NSOrderedAscending、NSorderedSame These enumeration values , Used to represent the size of collection elements . This method returns a sorted new NSArray object .
//----------------------------
// Yes NSArray Sort
#import <Foundation/Foundation.h>
#import "FKUser.h"
// Define a comparison function Based on the intValue Compare
NSComparisonResult intSort (id num1, id num2, void *context) {
int val1 = [num1 intValue];
int val2 = [num2 intValue];
if (val1 < val2) {
return NSOrderedAscending;
} else if (val1 > val2) {
return NSOrderedDescending;
} else if (val1 == val2) {
return NSOrderedSame;
}
return 0;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray *array = @[@"Objective-C", @"C", @"C++", @"Ruby", @"Perl", @"Swift"];
// Use set elements compare Methods the sorting
array = [array sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@ ", array);
// Initialize an element to NSNumber Of NSAarray object
NSArray* arr2 = @[
[NSNumber numberWithInt:20],
[NSNumber numberWithInt:12],
[NSNumber numberWithInt:-8],
[NSNumber numberWithInt:50],
[NSNumber numberWithInt:19]
];
// Use insort Sort
arr2 = [arr2 sortedArrayUsingFunction:intSort context:nil];
NSLog(@"%@", arr2);
// Use code blocks to sort collection elements
NSArray* arr3 = [arr2 sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 intValue] > [obj2 intValue]) {
return NSOrderedDescending;
} else if ([obj1 intValue] < [obj2 intValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}];
NSLog(@" %@", arr3);
}
return 0;
}
Sort attention
- For three sorting methods The first 2 One is that we write our own internal judgment criteria ,
- The third is to write internal standards for blocks
- The collection element itself can compare sizes , And the method of sorting directly by comparing the size of set elements is called natural sorting ; For the way to specify custom comparison rules by comparing functions or code blocks , Is called custom sorting .
Enumeration traversal NSArray Collection elements
Enumeration in reverse order
about NSArray object , except According to the set Combine the index of elements to traverse outside the collection elements , You can also call NSArray Object to return the enumerator .
- objectEnumerator: return NSArray The sequential enumerator of the collection .
- reverseObjectEnumerator: return NSArray An enumerator in reverse order of a collection
Both of the above methods return a NSEnumerator Enumerator , The enumerator contains only the following two methods
allobjects: Gets all the elements in the enumerated collection .
nextObiect: Gets the next element in the enumerated collection .
Generally speaking , With the help of nextObeiat Method to enumerate the collection elements : The program can continuously acquire nextObject Return value of method , Until the return value of the method is nil End of cycle .
// 7.5.4---- Enumeration in positive and negative order
#import <Foundation/Foundation.h>
#import "FKUser.h"
int main( int argc, char* argv[]) {
@autoreleasepool {
// Read the file Documents written before
NSArray *array = [NSArray arrayWithContentsOfFile:@"myFile.txt"];
// obtain NSArray Sequential enumerator
NSEnumerator *en = [array objectEnumerator];
id object;
while (object = [en nextObject]) {
NSLog(@"%@", object);
}
NSLog(@" Get the reverse enumerator ");
en = [array reverseObjectEnumerator];
while (object = [en nextObject]) {
NSLog(@" %@", object);
}
}
}
Quick enumeration
Quick enumeration (for - in)
OC- Provides a quick enumeration method to facilitate collection There is no need to get the length of the set to traverse the set using the fast enumeration method , There is no need to access collection elements according to the index You can quickly enumerate and traverse each element of the collection
Grammar goes down
for (type variableName in collection) {
variableName Automatically access each element
}
type yes Collection element type variableName Is a parameter name , Through quick enumeration, the set elements will be automatically assigned to the formal parameter variable in turn
#import <Foundation/Foundation.h>
#import "FKUser.h"
int main( int argc, char* argv[]) {
@autoreleasepool {
NSArray *array = [NSArray arrayWithContentsOfFile:@"myFile.txt"];
for (id object1 in array) {
NSLog(@"%@", object1);
}
}
}
About quick enumeration
As can be seen from the above procedure Using fast enumeration to traverse array elements does not need to get the array length There is no need to access array elements according to the index
The essence is (for-each) loop
for each
This cycle does not require cycle conditions There is no need to iterate over loop statements When each element is iterated once The cycle ends automatically
Variable array (NSMutableArray)
and NSArray Something different
- NSArray Represents an immutable set once NSArray Create success The program cannot add new elements to the collection , You cannot delete an existing element in the collection , Nor can you replace collection elements
- Be careful NSArray Just save the pointer of the object , therefore NSArray Only ensure that the addresses of these pointer variables do not change , But the object pointed to by the pointer variable can be changed
- NSMutableArray yes NSArray Subclasses of , So it can be used as NSArray Use
New operation
NSMutableArray Represents a set with variable set elements , and NSMutableArray The bottom layer uses traditional arrays to hold collection elements
therefore Create a NSMutableArray When collecting, you can specify the capacity of the underlying array through parameters
NSMutableArray New method
- Add collection elements ;add start
- Delete collection elements remove start
- Replace collection elements replace start
- Sort the set itself sort start
NSMutableArray yes NSArray Subclasses of So he also has 3 Sort by Be careful NSMutableArra Is a variable array set So it returns itself ( You can think of sorting the set itself )
NSArray It is Return a new sorted NSArray object
NSArray Of KVC and KVO( This article does not explain , I haven't learned relevant knowledge about monitoring for the time being )
NSArray Of KVC
- NSArray It allows you to directly integrate all the elements in the collection KVC code ,NSArray The following two codes are provided
- setValue: forKey: All elements in the collection are assigned key The corresponding attribute or instance variable is set to value
- valueForKey: Return to the NSArray The designation of all elements in the collection key Composed of NSArray object
#import <Foundation/Foundation.h>
#import "FKUser.h"
// Define a function hold NSArray Set to string
NSString* NSCollectToString(NSArray *array) {
NSMutableString* result = [NSMutableString stringWithString:@"["];
for (id obj1 in array) {
[result appendString:[obj1 description]];
[result appendString:@", "];
}
// Get string length
NSUInteger len = [result length];
// Discard the last two characters of the string
[result deleteCharactersInRange:NSMakeRange(len-2, 2)];
[result appendString:@"]"];
return result;
}
int main( int argc, char* argv[]) {
@autoreleasepool {
NSArray *array = @[
[[FKUser alloc]initWithName:@"sun" pass:@"123"],
[[FKUser alloc]initWithName:@"bai" pass:@"345"],
[[FKUser alloc]initWithName:@"zhu" pass:@"654"],
[[FKUser alloc]initWithName:@"tang" pass:@"178"],
[[FKUser alloc]initWithName:@"niu" pass:@"155"],
];
// Get all collection elements name A new set of attributes
id newArr = [array valueForKey:@"name"];
NSLog(@"%@", NSCollectToString(newArr));
// for (int i = 0; i < array.count; i++) {
// NSLog(@"%@", newArr[i]);
// }
// All elements of the set are KVC Programming
// For all set elements name Attribute to “ New name ’
[array setValue:@" Li Yuteng " forKey:@"name"];
// NSLog(@"%@", NSCollectToString(array));
for (int i = 0; i < array.count; i++) {
NSLog(@"%@", array[i]);
}
}
}
Strange print
The print result does not describe the nature of the array elements
The reason why the print result is as follows is that I didn't rewrite about description Method
rewrite description The result of the method
边栏推荐
猜你喜欢
Nacos 的安装与服务的注册
注意力机制的一种卷积替代方式
Esp8266-rtos IOT development
704 binary search
【嵌入式】使用JLINK RTT打印log
MYSQL卸载方法与安装方法
UML diagram memory skills
[today in history] February 13: the father of transistors was born The 20th anniversary of net; Agile software development manifesto was born
LeetCode:498. 对角线遍历
多元聚类分析
随机推荐
A convolution substitution of attention mechanism
LeetCode:34. Find the first and last positions of elements in a sorted array
Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
Advanced Computer Network Review(4)——Congestion Control of MPTCP
Esp8266-rtos IOT development
BN折叠及其量化
Pytest参数化你不知道的一些使用技巧 /你不知道的pytest
IJCAI2022论文合集(持续更新中)
KDD 2022论文合集(持续更新中)
[Hacker News Weekly] data visualization artifact; Top 10 Web hacker technologies; Postman supports grpc
[MySQL] limit implements paging
Deep anatomy of C language -- C language keywords
I-BERT
数字人主播618手语带货,便捷2780万名听障人士
在QWidget上实现窗口阻塞
opencv+dlib实现给蒙娜丽莎“配”眼镜
随手记01
Advanced Computer Network Review(5)——COPE
[sword finger offer] serialized binary tree