Programming style in Objective C question

Discussion in 'Mac Programming' started by John Baughman, Sep 24, 2009.

  1. John Baughman macrumors member

    Joined:
    Oct 27, 2003
    #1
    In programming other languages over the years I have tended to a minimalist style of programming which I find myself doing now as I am learning Objective-C.

    For example, I would write...

    Code:
    NSLog(@"Section 2\nName: %@  Process ID: %i\n\n", [[NSProcessInfo processInfo] processName], [[NSProcessInfo processInfo] processIdentifier]);
    
    Instead of...

    Code:
    NSString *processName = [[NSProcessInfo processInfo] processName];
    int processIdentifier = [[NSProcessInfo processInfo] processIdentifier];
    NSLog(@"Section 2\nName: %@  Process ID: %i\n\n", processName, processIdentifier);
    
    Obviously here I have no intention of using processName or processIdentifier anywhere else in the program. I tend to do this a lot.

    I am wondering if I am setting myself up for problems later on with regard to garbage collection or perhaps something else. If garbage collection is an issue, will using the Garbage Collector keep me out of trouble?

    Thanks,

    John
     
  2. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #2
    In GC mode that should always be safe*. In retain-release mode it will be safe as long as you make sure to follow the usual rules about retain counts.

    To elaborate on the last point, this will leak in R-R mode:
    Code:
    NSLog(@"%@", [[NSMutableArray alloc] initWithObject:@"aString"]);
    
    but neither of these will:

    Code:
    NSLog(@"%@", [NSMutableArray arrayWithObject:@"aString"]);
    
    Code:
    NSLog(@"%@", [[[NSMutableArray alloc] initWithObject:@"aString"] autorelease]);
    

    *for regular ObjC objects. CFRetain, CFCreate*, and CFCopy* will need a CFMakeCollectable() to balance them.
     
  3. John Baughman thread starter macrumors member

    Joined:
    Oct 27, 2003
    #3
    Thanks Catfish_Man,

    So using GC, I can safely continue my minimalist approach.

    Hillegass' book tended to confuse me regarding garbage collection. I have just started taking the Stanford course on iPhone development and I see that they are going to get into the subject, so hopefully that will clear things up for me.

    Do you know of a good book, or on line source that clearly explains how to handle garbage collection both with and without GC? I like rules of thumb and with garbage collection there does not seem to be any.

    Thanks again,
    John
     
  4. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #4
  5. John Baughman thread starter macrumors member

    Joined:
    Oct 27, 2003
    #5
    I was referring to garbage collection in general not GC. Maybe I am using the wrong terminology. When I think of garbage collection I think of retain/release of which, as I understand it, the Garbage Collector (GC) handles for you. As for the Stanford course, In the second class the instructor states that the course will get into memory management later and the course shows that topic in week 2. I would think that would entail some discussion of retain/release.

    John
     
  6. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #6
    The garbage collector does not work via automatic reference counting (calling retain and release for you). It's a traditional generational mark-and-sweep collector, quite unrelated to the retain/release model that the iPhone and many existing Mac apps use.

    GC is an acronym for garbage collection.
     
  7. John Baughman thread starter macrumors member

    Joined:
    Oct 27, 2003
    #7
    Ok. Thanks for the clarification. In your first response you referred to "GC mode" which was the first time I had seen the acronym GC. I thought GC was referring to the garbage collector.

    Please bear with me on this.

    If I have Objective-C Garbage Collection set to unsupported, I then must manage garbage collection manually using retain/release, right?

    If I have Garbage Collection set to supported, then I no longer need to manage GC manually with retain/release.

    If I am good so far then I think the following rephrasing of my comment would be correct...

    "When I think of garbage collection (GC), I think of retain/release of which the Garbage Collector, if turned on, relieves me."

    How the Garbage Collector does it's thing I now know is not by retain/ release but by mark-and-sweep. For the moment I have no idea what mark-and-sweep is, but at least I think you have given me a better general understanding of GC and the Garbage Collector. I intend to spend some quality time this week with the documentation on GC.

    Thanks,

    John
     
  8. autorelease macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #8
    The term you are looking for is memory management.

    Retain/release and garbage collection are two different kinds of memory management.

    Garbage collection is automatic memory management; the program figures out when objects aren't in use anymore and frees them.

    Retain/release is manual memory management. You have to specify when you're finished with something (release) and when you're using something (retain). An object is freed when everything holding onto it has released it (its retain count has reached zero). "Autorelease" basically means "release this object automatically after a little while."

    I think it's better for a new programmer to strictly use manual memory management, and only switch to garbage collection once he/she has a good grasp on the concept. It's kind of like how in school you had to take math tests without a calculator in order to properly learn the techniques. Learning the shortcuts first leads to confusion later on.
     
  9. GorillaPaws macrumors 6502a

    GorillaPaws

    Joined:
    Oct 26, 2003
    Location:
    Richmond, VA
    #9
    Am I the only one who finds the 2nd version more readable than the first. I can appreciate the logic behind the first version when the scope of your variables is limited to just that line, but the 2nd version is nicely broken up into simple digestible chunks. Stylistically, it's like the difference between the wall-of-text paragraph and one that's been broken up with whitespace to my eyes.

    I can't help but wonder if the impression I have here is the result of still being new to programming, and that my attitude will shift as my programming knowledge/experience matures. Is the more compact style the hallmark of more experienced programmers? or is it simply a matter of personal taste?
     
  10. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #10
    Clarity over compactness is a valuable thing, but exactly what level of complexity within a line counts as "unclear" changes as you get more used to reading code. For me, the original example just reads as "meh, debug logging", and my brain won't even bother figuring out what it's doing unless I need to know what it's logging. With it split onto multiple lines I have to check whether the local vars are only used for logging before I can mentally discard it.
     
  11. whooleytoo macrumors 603

    whooleytoo

    Joined:
    Aug 2, 2002
    Location:
    Cork, Ireland.
    #11
    If you're developing on the iPhone (or on Mac without Garbage Collection), the rules are relatively simple (in this post "object" refers to instances of NSObject or any subclass) :

    - If you create an object (via alloc, copy, or new methods), then you are responsible for sending it a release at some point. (or autorelease, see below).

    - If you receive an object from other methods (e.g. arrayWithObject..), you are not responsible for releasing it, and should not do so.

    - Any object returned from such other methods are only guaranteed to be valid in the current scope. If you require them later (most commonly - if you assign them to an instance variable in the current class), you must send them a retain.

    - If you send an object a retain, you are responsible for sending it a release, or autorelease at some point.

    And one final rule, a problem you might have spotted:

    - If you wish to create an object (via alloc, copy, new) and return it from your method, then you cannot release it before returning. In this case, use autorelease. (Read up on NSAutoreleasePools for details).

    Or to summarise loosely:

    Alloc, new, copy and retain increase the reference count; release and autorelease decrease it. You need to pair every alloc, new, copy or retain with a matching release or autorelease*.

    (*with autorelease being for the purpose of returning an object you just created, while ensuring it's properly released).
     
  12. John Baughman thread starter macrumors member

    Joined:
    Oct 27, 2003
    #12
    Thanks to all of you who have replied to my post, especially to whooleytoo and Catfish_Man. whooleytoo, I have printed out your guidance, which look to be the rules of thumbs I was looking for.

    I still have a few lingering questions, but will hold them back until I get a bit further along in my studies.

    John
     
  13. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #13
    Actually, he's just paraphrased Apple's Memory Management Guide. On the Cocoa-Dev list, such paraphrasing is actively discouraged, because such paraphrasings are often wrong in some important detail.

    What you should do is read the Memory Management Guide itself, become familiar with fundamental concepts like ownership, from which the rules derive, then come up with your own rules of thumb. I also recommend re-reading the Guide on occasion, and revising your rules of thumb.

    http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

    Quoting from "Who Should Read This Document":

    You should read this document to learn about the object ownership policies and related techniques for creating, copying, retaining, and disposing of objects in a reference-counted environment.

    This is true even if you think you can get by with just rules of thumb.

    By the way, that Guide is the top hit when googling keywords: cocoa memory management.
     

Share This Page