Struggling with this Chapter! Line-by-line explaination


#1

I’m really struggling with this chapter. I have read this chapter several times over; even re-read from chapter 11 to try to understand what is going on in the code; however, I still find my self lost.

Below is an attempt to explain each line in every file that I think the code is doing. Can someone please correct me where I’m wrong and answer the questions below each file?

I feel frustrated and stuck! I tried doing chapter 20 and quickly realized that until I grasp a good understanding of Chapter 19, I cannot proceed.

Thank you in advance!

Asset.h

#import <Foundation/Foundation.h>
@interface Asset : NSObject //Inherits NSObject
{
    NSString *label; //Declare a pointer to a NSString variable called "label"
    unsigned int resaleValue; //Declare an unsigned integer called "resaleValue"
}
@property (strong) NSString *label;  //Declare setter and getter to a NSString variable called "label" and claims ownership (strong)
@property unsigned int resaleValue; //Declare setter and getter to an unsigned integer "resaleValue"
@end

Asset.m

#import "Asset.h"
#import "Employee.h"

@implementation Asset
@synthesize label, resaleValue; //Tells complier to synthesize default accessor methods on "label" and "resaleValue"

- (NSString *)description //Define and overrides description:  Returns a NSString pointer to an instance of "description" 
{
     //return a NSString stringWithFormat of "self label" which is a pointer to an object and "self resaleValue" which is an Integer    
     return [NSString stringWithFormat:@"<%@: $%d>", [self label], [self resaleValue]];
                                  
}

- (void)dealloc //Define and override dealloc: returns and accepts nothing
{
    NSLog(@"deallocating %@", self); //Print "self" when deallocating
}
@end

Q’s for Assets.m (code above):

Q1: Did I explain the lines below correctly?

  • (NSString *)description //Define and overrides description: Returns a NSString pointer to an instance of “description”
    {
    //return a NSString stringWithFormat of “self label” which is a pointer to an object and “self resaleValue” which is an Integer
    return [NSString stringWithFormat:@"<%@: $%d>", [self label], [self resaleValue]];
    }

Q2: When defining and/or overriding dealloc, how does the method know how to deallocate? Which method or class is “self” coming from?

Employee.h

#import <Foundation/Foundation.h>
#import "Person.h" //Import Person.h
@class Asset; // Inform Employee.h that there exists a class called "Asset"

@interface Employee : Person //Inherit the "Person" class
{
    int employeeID; //Declare an integer "employeeID"
    NSMutableArray *assets; //Declare a pointer to an array called "assets"
}
@property int employeeID; //Setter and getter methods for employee ID

-(void)addAssetsObjects:(Asset *)a; //Declare a method called "addAssetsObjects" that accepts a pointer to an instance object of "Asset" called "a"
-(unsigned int)valueOfAssets; //Declare a method called valueOfAssets that returns an  unsigned integer

@end

Q3: In Employee.h (above): Why do we NOT do “@property NSMutableArray *assets;” ?

Employee.m

#import "Employee.h" //Import Employee.h
#import "Asset.h" //Import Asset.h

@implementation Employee

@synthesize employeeID; //Synthesize employeeID

-(void)addAssetsObjects:(Asset *)a //Define the method called "addAssetsObjects" that accepts a pointer to an instance object of "Asset" called "a"
{
    //If assets array does not exist, create it.  
    if (!assets){
        assets = [[NSMutableArray alloc] init];
    }
    [assets addObject:a]; //In the assets Array, add the pointer to an instance object of "Asset" called "a"
}

-(unsigned int)valueOfAssets //Define the method called valueOfAssets that returns an unsigned integer
{
    unsigned int sum = 0; //Declare sum as a local unsigned integer (variable) and assign a value of "0"
    for (Asset *a in assets){ //fast enumeration of "assets" array that goes through every object in the array
        sum+= [a resaleValue]; //Add to the value of sum -- I'm not sure what it means by "[a resale value]"
    }
    return sum; //returns the total value of sum
}

Q4: In Employee.m (above), the line: “sum+= [a resaleValue];” says to add to the value of “sum”. What does “[a resaleValue]” mean?

main.m

#import <Foundation/Foundation.h>
#import "Person.h" //import "Person.h"
#import "Employee.h" //import "Employee.h"
#import "Asset.h" //import "Asset.h"


int main(int argc, const char * argv[])
{

    @autoreleasepool {
    
        NSMutableArray *employees = [[NSMutableArray alloc] init]; //Create an array called "employees"
        for (int i = 0; i<10; i++){  //Do a for-loop 10 times (0 - 9)
            
            Employee *person = [[Employee alloc] init]; //create a pointer to an "Employee" instance object called "person"
            [person setWeightInKilos:90+i]; //Set value for "weightInKilos" in "person" instance object
            [person setEmployeeID:i]; //Set value for "employeeID" in "person" instance object
           
            [employees addObject:person]; //store the instance object "person" in the employees array
        }
        
        for (int i = 0; i < 10; i++) { //Run the for-loop 10-times
            Asset *asset = [[Asset alloc] init]; // Create a pointer to an "Asset" instance object called asset 
            
            NSString *currentLabel = [NSString stringWithFormat:@"Laptop %d", i]; //Create a pointer to "NSString" instance object called "currentLabel" and assign a format. 
            [asset setLabel:currentLabel]; //Set value for "label" in "asset" instance object to "currentLabel"
            [asset setResaleValue:i*17]; //Set value for "resaleValue" in "asset" instane object to "i*17"
            
            NSUInteger randomIndex = random() % [employees count];//All I an understand in this that "count" returns the number of items in "employees" array.  Please explain?
            
            Employee *randomEmployee = [employees objectAtIndex:randomIndex]; //Create a pointer to an "Employee" instance object called "randomEmployee".  Not sure what does [employees objectAtIndex:randomIndex] does?  "Employee" is a class and "employees" is an array.  I can't figure out what's going on in this line?
            [randomEmployee addAssetsObjects:asset]; //Store the instance of "asset" into "randomEmployee" array.

        }
        
            NSLog(@"Employees: %@", employees); //Prints the "employees" array.  Can you use NSLog to print an entire array?
            NSLog(@"Giving up ownership of one employees"); //prints the message
            [employees removeObjectAtIndex:5]; //removes Object at index 5 in the employees array
            NSLog(@"Giving up ownership of array"); //prints the message
        
        employees = nil; //sets employees to nil giving up the ownership of the array.  Does deallocating begin at index 0 or it's random?
    }

    return 0;
}

Questions for main.m (above)
Q5: NSUInteger randomIndex = random() % [employees count]; //All I can understand in this that “count” returns the number of items in “employees” array. Need help understanding this entire line.

Q6: Employee *randomEmployee = [employees objectAtIndex:randomIndex]; //Create a pointer to an “Employee” instance object called “randomEmployee”. Not sure what does [employees objectAtIndex:randomIndex] does? “Employee” is a class and “employees” is an array. I can’t figure out what’s going on in this line, please explain?

Q7: NSLog(@“Employees: %@”, employees); //Prints the “employees” array. Can you use NSLog to print an entire array? We don’t need to specify that it is an array and to print every object until it reaches nil?

Q8: employees = nil; //sets employees to nil giving up the ownership of every object in the array. Does deallocating begin at index 0 or is it random?


#2

I am trying to figure out how to help you.

What chapter did you start reading the book from?
You should start with chapter 1 and read and code all chapters, with an open mind.

Can you program in C or C++?
A competent C or C++ programmer should find reading and understanding this book a breeze because the Author has done an excellent job considering the physical size of the book.

Also. Apple provides good documentation on the Objective-C language. For example, Learning Objective-C: A Primer.


#3

[quote]Q1: Did I explain the lines below correctly?

  • (NSString *)description
    {
    return [NSString stringWithFormat:@"<%@: $%d>", [self label], [self resaleValue]];
    }
    [/quote]
    Yes.

When you write code for a class, you write code to create objects (at strategic points) if instances of that class need objects; so you know what to deallocate in the dealloc method:

[code]
@interface Widget: NSObject
{
// Declare instance variables here
// …
}

// Declare properties here
// …

// Declare methods here
// …

@end

@implementation Widget

  • (id)init
    {
    // Always invoke super’s init, and invoke it first.
    self = [super init];
    if (self)
    {
    // Create (and retain) objects here if you need any
    //
    }
    return self;
    }

  • (void)dealloc
    {
    // Deallocate objects here if you have created (and retained) them
    // …

    // Always invoke the super’s dealloc, and invoke it last
    [super dealloc];
    }

  • (void)doSomeWork
    {
    // Here we create a gadget object (and retain it )because we will need it later
    // …
    }

@end[/code]

As for self, it is a pointer to the object (a pice of data in memory) created as an instance of the class containing the instance method where self appears. And, inside a class method, self points to the object representing that class.


#4

@ibex10

Thank you for answering 2 of the 8 questions.

I started the book from Part 1: Getting Started. First paragraph in chapter 1 states that you don’t need any programming experience to read this book. I also did all the code and challenges with an “open mind”.

I do not have any C or C++ programming background since this was not the requirement to read this book. Thus, I can understand why this book would be a breeze for a competent C or C++ programmer.

I’m not sure as to why you were confused on how to help me. I have included codes from 5 files. I have gone through each line in each of the files and put in my comments explaining what I think each code does. If someone has the time, I would greatly appreciate them looking at the comments and correcting me where I’m wrong. Additionally, I have 8 questions that I would like to have answers for. I’m hoping these answers to these 8 questions would help me better understand the code.

You are right, the Author did do a fantastic job with this book, as I have had no problems with the first 18 chapters! I know I’m not the sharpest tool on the shelf, however, it appears that there are several others that are struggling with this chapter as well. You can confirm this by looking at the amount of posts (221) and replies (57) Chapter 19 has – no other chapter has that many posts or replies in the forum.

I appreciate you offering to help, but your first post was very discouraging.