相关疑难解决方法(0)

在Objective-C中复制块(即:将它们复制到实例变量)

我想了解块.当直接传递给方法时,我得到了正常使用它们的方法.我现在感兴趣的是一个块,将它(例如)存储在一个实例变量中并稍后调用它.

块编程指南听起来像我可以做到这一点,通过使用Block_copy/retain来复制块,但是当我尝试运行它时,我崩溃了我的程序.

- (void) setupStoredBlock
{
    int salt = 42;
    m_storedBlock = ^(int incoming){ return 2 + incoming + salt; };
    [m_storedBlock retain];
}
Run Code Online (Sandbox Code Playgroud)

我试着稍后再说:

- (void) runStoredBlock
{
    int outputValue = m_storedBlock(5);
    NSLog(@"When we ran our stored blockwe got back: %d", outputValue);
    [m_storedBlock release];
}
Run Code Online (Sandbox Code Playgroud)

有人有任何见解吗?(或者,有什么东西我没有用积木?)

非常感谢你!

cocoa objective-c objective-c-blocks

19
推荐指数
3
解决办法
1万
查看次数

Objective C复制并保留

所以,只是一个简单的问题,我何时应该使用copy而不是使用retain.我试图从互联网上看,但没有得到它.有人可以照亮我吗?

copy objective-c retain

8
推荐指数
2
解决办法
2万
查看次数

保留/复制自动释放的对象

我想确保我在这里正确理解内存管理.有没有什么特别的理由在这里使用其中一个assignCurrentDate方法?而且,所有这些都导致没有内存泄漏,对吗?

在.h我们有:

NSDate *currentDate1;
NSDate *currentDate2;
NSDate *currentDate3;
NSDate *currentDate3; 
//and 
@property (nonatomic, retain) NSDate *currentDate1;
@property (nonatomic, retain) NSDate *currentDate2;
@property (nonatomic, retain) NSDate *currentDate3;
@property (nonatomic, retain) NSDate *currentDate4;
Run Code Online (Sandbox Code Playgroud)

在他们中:

-(void) assignCurrentDate1
{
currentDate1 = [[NSDate date]retain];
//[NSDate date] is autoreleased
}

-(void) assignCurrentDate2
{
currentDate2 = [[NSDate date]copy]; 
}

-(void) assignCurrentDate3
{
self.currentDate3 = [NSDate date];
}

-(void) assignCurrentDate4
{
currentDate4 = [[NSDate alloc]init];
//[[NSDate alloc]init] is not autoreleased.
}

-(IBAction) printDate
{
NSLog ("%@", currentDate1);
NSLog …
Run Code Online (Sandbox Code Playgroud)

iphone memory-management objective-c

4
推荐指数
1
解决办法
670
查看次数