Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

automatic ref counting - iOS: How to remove object from memory with ARC enabled?

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?

EDIT: 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];

The sparkle object code:

#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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Object* myObject = [[Object alloc] init];     
myObject = nil; // poof...

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...