[home] [blog] [services] [portfolio] [contact]
Shortlink

Frustrated by “pointer being freed was not allocated”?

I spent a few hours today trying to determine the cause for a bunch of rogue “pointer being freed was not allocated” message when my objects fell out of scope. I thought I had perfectly followed the Apple guidelines for malloc/free calls under an ARC managed application. I was using a lot of char pointers, NSData objects and so forth, but it turns out I missed one thing: [NSData dataBytesWithNoCopy]. I was avoiding using it in general because I wanted to make sure any allocated pointers I passed in were being freed properly, and didn’t have enough experience or time to test if ARC handles it all properly. I continued to use it with statically initialized char[] arrays figuring that NSData would have no problem not needing to clean it up. If you didn’t know, you don’t need to free() character arrays such as: char myData[] = { 0×00, 0×01, 0×02 }; The rule is only to use free() with malloc/calloc calls.

So why all the fuss? It would appear NSData doesn’t understand when you initialize with a char array that it doesn’t need to free() it. For example, this code will cause the error to appear when ARC deallocates the NSData object (or rather the internal NSConcreteData class).

unsigned char table1DataBytes[] = { 0x01,0x01,0x01,0x01,0x01 };
NSData *table1Data = [NSData dataWithBytesNoCopy: table1DataBytes length: sizeof(table1DataBytes)];

So if this is something you did, simply switch to [NSData dataWithBytes] and the world seems alright again.

EDIT: As someone on the Apple Developer forums also pointed out, you can also add in the freeWhenDone: NO parameter to dataWithBytesNoCopy and NSData will not free the object. Didn’t even see that there in the reference good catch and the preference over copying the data!

Shortlink

Objective-C is wordy.

So I decided to spend most of today (and the previous few days) finally learning Objective-C so I can get around to completing about 4 iPad app projects that I’ve been putting off.

As I’ve come to discover, Objective-C was designed by the devil. In Apple’s quest to create things cool and different they gave birth to the bastard child that is Objective-C. (well, not Apple itself but you go google that yourself).

Objective-C takes a rather different approach to how you think about writing programs. Instead of calling “methods” you send “messages” using what only appears as an abomination of programming syntax (read: nested square brackets that make my eyes bleed). I’m used to programming languages that seem to all make sense in my head: C#, Java, PHP, Javascript, C++, hell even Basic. Objective-C (hereafter referenced as OMG-C) uses a very wordy syntax with very long naming conventions within the iOS framework making it read somewhat like a short story with some math symbols thrown around for fun.

Presumably this is the guy who invented OMG-C in his mom's basement

So here I am, trying to educate myself on how to perform basic memory management using my trusty written in paper guide. To my discovery iOS 5 has implemented a new memory management system called ARC – Automatic Reference Counting. See OMG-C uses reference counting to keep track of memory cleanup – if you alloc something, make sure you release it. ARC still requires you to alloc your objects but you no longer need to release them; they will be removed when your object has fallen out of scope and no longer is referenced. Kind of like .Net Garbage collection but really more like reference counting. I hope you detect my sarcasm here.

I’m about 500 pages into my short story about 2 buttons and 1 label on my iPad simulator when OMG OMG OMG there’s a spider on my screen. I completely lost my train of thought. I spent the last 5 hours studying reference material and trying to learn how OMG-C is supposed to help me create programs on the iPad and I was caught so off-guard by this giant bastard of a spider that I completely forgot everything I learned. WTH. Needless to say I sprayed the 7 legged a**hole (he must have lost it in a previous engagement) with WD40 and lit it on fire while running away screaming into a far corner of the house. He got all the way from the Run button to the Object Library before falling into a heap of black soot on top of a stack of post-it-notes (I see what you did there).

An accurate rendering of the little bastard that invaded my Mac

Tomorrow I will attempt to write my first iPad application again if I can work up the courage to go near my desk. I’m really looking forward to understanding why the hell boolean’s are YES/NO and NULL’s are nil. It’s like I’m inside Steve Jobs (RIP) personal house of mirror’s.

On an unrelated note I need a new Mac to learn OMG-C on so if anyone wants to donate to the “Spiders Suck-It” fund it would be appreciated.

Shortlink

Design Patterns: Decorator

The Decorator pattern is used when an abstraction from the original object is needed from properties that need to be added to the original object.

For example, we may want to add a border to an object instance and not the entire class. Sure, you could simply add a ‘border’ property to the class – but what happens when the object isn’t even aware that it may need a border added? Such a case may be when you want to add a scroll bar to an object without the object being aware of what a scroll bar is. Of course this can be applied outside of a user interface – there are many other examples out there such as this one: http://www.dofactory.com/Patterns/PatternDecorator.aspx

Here’s my application of the pattern to add padding, or a border to an HTML image or HTML5 video tag.

class DecoratorPattern2
	{
		public DecoratorPattern2()
		{
			// Participants:
			// Component (Visual)
			// ConcreteComponent
			// Decorator
			// ConcreteDecorator (BorderDecorator, ScrollDecorator)

			DisplayImage image1 = new DisplayImage("/images/image.png", "This is an image", 640, 480);
			DisplayVideo video1 = new DisplayVideo("/videos/video.mp4", "This is a test video", "controls", 520, 319);

			BorderDecorator imageborderDecorator = new BorderDecorator(image1);
			PaddingDecorator imagepaddingDecorator = new PaddingDecorator(image1);
			PaddingDecorator videopaddingDecorator = new PaddingDecorator(video1);

			image1.Render();
			video1.Render();
		}
	}

	/// <summary>
	/// The 'Component' abstract class
	/// </summary>
	public abstract class DisplayObject
	{
		private int width = 320;
		private int height = 240;
		private string additionalOptions = "";

		public int Width
		{
			get { return width; }
			set { width = value; }
		}

		public int Height
		{
			get { return height; }
			set { height = value; }
		}

		public string AdditionalOptions
		{
			get { return additionalOptions; }
			set { additionalOptions = value; }
		}

		public abstract void Render();
	}

	/// <summary>
	/// The 'ConcreteComponent' class
	/// </summary>
	public class DisplayImage : DisplayObject
	{
		private string src;
		private string caption;

		public DisplayImage(string src, string caption, int width, int height)
		{
			this.src = src;
			this.caption = caption;
			// Base class properties
			this.Width = width;
			this.Height = height;
		}

		public override void Render()
		{
			Console.WriteLine("<img src='{0}' alt='{1}' title='{1}' width='{2}' height='{3}' style='{4}'>\n", this.src, this.caption, this.Width, this.Height, this.AdditionalOptions);
		}
	}

	/// <summary>
	/// Another 'ConcreteComponent' class
	/// </summary>
	public class DisplayVideo : DisplayObject
	{
		private string src;
		private string caption;
		private string controls;

		public DisplayVideo(string src, string caption, string controls, int width, int height)
		{
			this.src = src;
			this.caption = caption;
			this.controls = controls;
			// Base class properties
			this.Width = width;
			this.Height = height;
		}

		public override void Render()
		{
			Console.WriteLine("<video src='{0}' title='{1}' controls='{2}' width='{3}' height='{4}' style='{5}'></video>\n", this.src, this.caption, this.controls, this.Width, this.Height, this.AdditionalOptions);
		}
	}

	/// <summary>
	/// The 'Decorator' abstract class
	/// </summary>
	public abstract class Decorator : DisplayObject
	{
		protected DisplayObject displayObject;

		// we add the 'ConcreteComponent' item inside the decorator so we know what to decorate
		public Decorator(DisplayObject displayObject)
		{
			this.displayObject = displayObject;
		}

		public override void Render()
		{
			displayObject.Render();
		}
	}

	/// <summary>
	/// The 'ConcreteDecorator' class allows attaching extra data to an object - in this case adding a border
	/// </summary>
	public class BorderDecorator : Decorator
	{
		private string borderProperties = "border: 1px solid #000; ";
		public BorderDecorator(DisplayObject displayObject) : base(displayObject)�
		{
			base.displayObject.AdditionalOptions += borderProperties;
		}

		public override void Render()
		{
			base.Render();
		}
	}

	/// <summary>
	/// The 'ConcreteDecorator' class allows attaching extra data to an object - in this case adding padding
	/// </summary>
	public class PaddingDecorator : Decorator
	{
		private string paddingProperties = "padding: 5px; ";
		public PaddingDecorator(DisplayObject displayObject)
			: base(displayObject)
		{
			base.displayObject.AdditionalOptions += paddingProperties;
		}

		public override void Render()
		{
			base.Render();
		}
	}
Shortlink

Design Patterns: Observer

A very common design pattern is the Observer pattern. Where do we see Observer patterns in our code? Events and delegates. Essentially Events are a slightly modified version of a delegate, and delegates are an implementation of the observer pattern. An interesting article on this is available here if you are interested.

A simplified example of the Observer pattern can be seen below. This example shows how “subscribers” can be attached to a stock price and receive notifications when they change. In a real-world example we would accomplish this using events, or our send out notifications via network transmission instead of outputting to the screen.


class ObserverPattern
	{
		// Participants:
		// Subject
		// Observer
		// ConcreteSubject (optional)
		// ConcreteObserver (optional)

		public ObserverPattern()
		{
			IBM ibm = new IBM(120);
			ibm.Attach(new Investor("John Doe"));
			ibm.Attach(new Investor("Jane Doe"));

			// ok create a few fluctuating prices
			ibm.Price = 130;
			ibm.Price = 132;
			ibm.Price = 132.5;

		}
		
	}

	/// <summary>
	/// The Subject abstract class, as a Stock symbol
	/// </summary>
	public abstract class Stock
	{
		private string symbol;
		private double price;
		private List<IInvestor> investors = new List<IInvestor>();

		public double Price
		{
			get { return price; }
			set {
				// If the price has changed, notify the subscribers
				if (price != value)
				{
					price = value;
					Notify();
				}
			}
		}

		public string Symbol
		{
			get { return symbol; }
		}

		public Stock(string symbol, double price)
		{
			this.symbol = symbol;
			this.price = price;
		}

		public void Attach(IInvestor investor)
		{
			investors.Add(investor);
		}

		public void Detach(IInvestor investor)
		{
			investors.Remove(investor);
		}

		public void Notify()
		{
			foreach (IInvestor investor in investors)
			{
				investor.Update(this);
			}
		}
	}

	/// <summary>
	/// The ConcreteSubject class, as a specific Stock symbol
	/// </summary>
	public class IBM : Stock
	{
		public IBM(double price) : base("IBM", price) { }
	}

	public class Investor : IInvestor
	{
		private string name;
		private Stock stock;

		public Stock Stock
		{
			get { return stock; }
			set { stock = value; }
		}

		public Investor(string name)
		{
			this.name = name;
		}

		public void Update(Stock stock)
		{
			Console.WriteLine("To {0}: {1} changed to {2:C}", name, stock.Symbol, stock.Price);	
		}
	}

	/// <summary>
	/// The Observer interface/abstract class
	/// </summary>
	public interface IInvestor
	{
		void Update(Stock stock);
	}

Shortlink

Design Patterns: Factory

In the next continuation in design patterns we are going to use a very common one: Factory.

The Factory pattern is designed to deliver you an object of a given type based on your needs, such as an enumeration or some other designation.

In this example we use the factory to return an employee object of a given type. The employee object is an abstract class – but could easily be an interface – and we want to get a child class of a specific type.

For those of you who aren’t familiar with the Gang of Four book – I recommend purchasing “Design Patterns” by Gamma, Helm, Johnson & Vlissides (published by Addison-Wesley).

The code is pretty simple and is quite possibly the worst usage of the factory pattern – it’s purely for readability!

	// Participants:
	//   Creator
	//   ConcreteCreator (optional)
	//   Product
	//   ConcreteProduct (optional)
	class FactoryPattern
	{
		public FactoryPattern()
		{
			// The factory returns the object we want
			Employee executiveUser = EmployeeFactory.GetEmployee(EmployeeFactory.EmployeeType.Executive);
		}
	}

	///
	/// The Creator by default provides the implementation of the ConcreteCreator
	///
	public class EmployeeFactory
	{
		public enum EmployeeType
		{
			None,
			Manager,
			Programmer,
			Executive
		}

		public static Employee GetEmployee(EmployeeType employeeType)
		{
			Employee e = null;
			switch (employeeType)
			{
				case EmployeeType.Manager:
					e = new Manager();
					break;
				case EmployeeType.Programmer:
					e = new Programmer();
					break;
				case EmployeeType.Executive:
					e = new Executive();
					break;
			}
			return e;
		}
	}

	///
	/// The Product, a generic employee class
	///
	public abstract class Employee
	{
		private string name = "";
		private double salary = 0;

		public abstract string Name
		{
			get { return name; }
			set { name = value; }
		}

		public abstract double Salary
		{
			get { return salary; }
		}

		public abstract void LogStartTime();
		public abstract void LogEndTime();

		private Employee() { }
	}

	///
	/// A ConcreteProduct, an employee of a given type
	///
	public class Manager : Employee
	{
		private string name = "";
		private double salary = 75000;

		public override string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public override double Salary
		{
			get
			{
				return salary;
			}
		}

		public override void LogStartTime()
		{
			// log start time
		}

		public override void LogEndTime()
		{
			// log end time
		}
	}

	///
	/// A ConcreteProduct, an employee of a given type
	///
	public class Programmer : Employee
	{
		private string name = "";
		private double salary = 55000;

		public override string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public override double Salary
		{
			get
			{
				return salary;
			}
		}

		public override void LogStartTime()
		{
			// log start time
		}

		public override void LogEndTime()
		{
			// log end time
		}
	}

	///
	/// A ConcreteProduct, an employee of a given type
	///
	public class Executive : Employee
	{
		private string name = "";
		private double salary = 100000;

		public override string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public override double Salary
		{
			get
			{
				return salary;
			}
		}

		public override void LogStartTime()
		{
			// log start time
		}

		public override void LogEndTime()
		{
			// log end time
		}
	}