iOS:如何在启用ARC的情况下从内存中删除对象? [英] iOS: How to remove object from memory with ARC enabled?

查看:123
本文介绍了iOS:如何在启用ARC的情况下从内存中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iOS 5 SDK开发iOS应用程序,启用了自动引用计数。但是我有一个特定的对象正在大量创建,并且必须在一秒钟后释放,否则设备将变得非常慢。看起来它们没有被释放,因为设备非常慢。有没有办法在启用ARC时手动释放对象?

I am developing an iOS app with the iOS 5 SDK, Automatic Reference Counting is enabled. But I have a specific object that is being created in large numbers and must be released after a second because otherwise the device will become very slow. It looks like they are not released, as the device is very slow. Is there a way to manually release an object when ARC is enabled?

编辑:我的代码,每秒调用200次以产生闪光。它们在0.8秒后消失,因此在那之后它们没用了。

My code, this is called 200 times a second to generate sparkles. They fade out after 0.8 seconds so they are useless after then.

    int xanimationdiff = arc4random() % 30;
    int yanimationdiff = arc4random() % 30;
    if (arc4random()%2 == 0) {
        xanimationdiff = xanimationdiff * -1;
    }
    if (arc4random()%2 == 0) {
        yanimationdiff = yanimationdiff * -1;
    }

    Sparkle *newSparkle = [[Sparkle alloc] initWithFrame:CGRectMake(20 + arc4random() % 280, 20, 10, 10)];
    //[newSparkle setTransform:CGAffineTransformMakeRotation(arc4random() * (M_PI * 360 / 180))]; //Rotatie instellen (was niet mooi, net sneeuw)
    [self.view addSubview:newSparkle];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.8];
    [newSparkle setFrame:CGRectMake(newSparkle.frame.origin.x - xanimationdiff, newSparkle.frame.origin.y - yanimationdiff, newSparkle.frame.size.width, newSparkle.frame.size.height)];
    newSparkle.alpha = 0;
    [UIView commitAnimations];

闪光对象代码:

#import "Sparkle.h"

@implementation Sparkle

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"sparkle.png"]]];
    }
    return self;
}

@end


推荐答案

Object* myObject = [[Object alloc] init];     
myObject = nil; // poof...

编辑:您无法直接控制对象何时被释放但您可以间接控制导致它发生。怎么样?记住ARC确实做了什么。与人类编码约定不同,ARC解析您的代码并插入发布语句,因为即使是对象也可以发布。这可以立即释放内存以进行新的分配,这非常棒/必要。
含义,将对象设置为nil,或者只是允许变量超出范围......导致A 0 RETAIN COUNT的事情迫使ARC在其中放置其释放调用。
它必须......因为否则会泄漏。

You cannot directly control when an object is released BUT you can indirectly cause it to happen. How? Remember what ARC does EXACTLY. Unlike human coding convention, ARC parses your code and inserts release statements AS SOON AS OBJECTS CAN be released. This frees up the memory for new allocations straight away, which is awesome/necessary. Meaning, setting an object to nil, or simply allowing a variable to go out of scope ... something that CAUSES A 0 RETAIN COUNT forces ARC to place its release calls there. It must ... because it would leak otherwise.

这篇关于iOS:如何在启用ARC的情况下从内存中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆