// // main.m // NSArray和NSString之间转换 #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSArray *arr = @[@"lnj", @"lmj", @"jjj"]; // 需求: 用-将所有的姓名连接起来生成一个字符串 // 1.定义一个可变字符串保存拼接之后的结果 NSMutableString *strM = [NSMutableString string]; // 2.遍历数组, 取出数组中的每一个元素, 将元素添加到可变字符串中 for (NSString *str in arr) { [strM appendString:str]; // 3.每次添加完毕之后再添加一个- [strM appendString:@"-"]; } [strM deleteCharactersInRange:NSMakeRange(strM.length - 1, 1)]; //lnj-lmj-jjj NSLog(@"strM = %@", strM); NSString *str = [arr componentsJoinedByString:@"**"]; NSLog(@"str = %@", str);//lnj**lmj**jjj // 通过一个字符串生成一个数组 // 也叫做字符串切割 NSString *str1 = @"lnj**lmj**jjj"; NSArray *arr1 = [str1 componentsSeparatedByString:@"**"]; NSLog(@"arr = %@", arr1);//(lnj,lmj,jjj) return 0; }
// main.m // NSArray文件读写 #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { // 1.将数组写入到文件中 NSArray *arr = @[@"lnj", @"lmj", @"jjj"]; // 其实如果将一个数组写入到文件中之后, 本质是写入了一个XML文件 // 在iOS开发中一般情况下我们会将XML文件的扩展名保存为plist,xcode打开, BOOL flag = [arr writeToFile:@"/Users/mctc/Desktop/a.txt" atomically:YES]; /* <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>lnj</string> <string>lmj</string> <string>jjj</string> </array> </plist> */ flag = [arr writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES]; NSLog(@"flag = %i", flag); Person *p1 = [Person new]; p1.age = 10; Person *p2 = [Person new]; p2.age = 20; Person *p3 = [Person new]; p3.age = 5; Person *p4 = [Person new]; p4.age = 7; NSArray *arr1 = @[p1, p2, p3, p4]; // 注意:writeToFile只能写入数组中保存的元素都是Foundation框架中的类创建的对象, 如果保存的是自定义对象那么不能写入 BOOL flag1 = [arr1 writeToFile:@"/Users/mctc/Desktop/a.plist" atomically:YES]; NSLog(@"flag = %i", flag1); // 2.从文件中读取一个数组 NSArray *newArray = [NSArray arrayWithContentsOfFile:@"/Users/mctc/Desktop/a.plist"]; NSLog(@"%@", newArray);//(lnj,lmj,jjj) return 0; }
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7440677.html,如需转载请自行联系原作者