Foundation框架浅析 - NSAttributedString

1.instancetype 对比 id 

-》id可以作为函数参数,instancetype则不能

->在init方法中两者等价,编译器会自动保护将id 转换成 instancetype

如:

- (id)initWithBar:(NSInteger)bar;
- (instancetype)initWithBar:(NSInteger)bar;

-》在构造函数中则不一样,instancetype总是能返回正确的结果,id则不同。

以下是不等价的:

+ (id)fooWithBar:(NSInteger)bar;
+ (instancetype)fooWithBar:(NSInteger)bar;

使用第二种返回构造着时候,你每次都会得到正确的结果。

2.NSAttributedString

-》创建属性字符串

NSDictionary * attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],NSStrokeColorAttributeName,[NSNumber numberWithFloat:5.0f],NSStrokeWidthAttributeName, nil];
    NSAttributedString * str = [[NSAttributedString alloc]initWithString:@"hello world!" attributes:attributes];

-》获取字符串的属性

NSRange rage = NSMakeRange(0, 4);
    NSDictionary * dc = [str  attributesAtIndex:0 effectiveRange:&rage];

-》 NSMutableAttributedString,动态属性字符串,属性可以动态添加。

3.NSAutoreleasePool 用于管理被声明为autorelease的实例。

原理:在NSAutoreleasePool中包含了一个可变数组,用来存储被声明为autorelease的对象。当NSAutoreleasePool自身被销毁的时候,它会遍历这个数组,release数组中的每一个成员(注意,这里只是release,并没有直接销毁对象)。若成员的retain count 大于1,那么对象没有被销毁,造成内存泄露。默认的NSAutoreleasePool 只有一个,你可以在你的程序中创建NSAutoreleasePool,被标记为autorelease的对象会跟最近的NSAutoreleasePool匹配。可以嵌套使用NSAutoreleasePool。

缺点

        即使NSAutoreleasePool看起来没有手动release那么繁琐,但是使用NSAutoreleasePool来管理内存的方法还是不推荐的。因为在一个NSAutoreleasePool里面,如果有大量对象被标记为autorelease,在程序运行的时候,内存会剧增,直到NSAutoreleasePool被销毁的时候才会释放。如果其中的对象足够的多,在运行过程中你可能会收到系统的低内存警告,或者直接crash。

实例

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
ClassA *a=[[[ClassA alloc] init] autorelease];
ClassB *b=[[[ClassB alloc] init] autorelease];
ClassC *c=[[[ClassC alloc] init] autorelease];

[pool release];


4.NSCache类,区别于文件系统下得caches文件夹。

在ios中,苹果提供了,NSCache类和NSDictionary很相似,提供key,value的存储,不一样的是NSCache在内存吃紧的时候会做自动释放。

遇到一个问题是,在使用大量图片的app中,需要从存储里面读取数据,每次都从文件系统里面读取文件会造成卡顿现象。

解决办法就是把NSData对象缓存起来,先从NSCache里面读取数据,然后再从文件系统获取数据,提高效率。

NSArray * arr = @[@"hello",@"world"];
    NSCache * cache = [[NSCache alloc]init];
    [cache setObject:arr forKey:@"hello"];
    
     NSArray * tem = [cache objectForKey:@"hello"];

Printing description of tem:
<__NSArrayI 0x8ca4c00>(
hello,
world
)
Printing description of arr:
<__NSArrayI 0x8ca4c00>(
hello,
world
)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值