Quick & dirty object change tracking in C#

I ran into a issue the other day that was fairly straight forward to solve. I needed to see all of the properties that changed on a object since it was originally setup. The initial state of the object can be anything, either a freshly instanced object, a deserialized object or a object created by setting properties, one at a time during start up or something.

What I wanted to do was essentially perform a SQL update, that just updated the properties that were changed when the user presses a save button. So by creating a Initialize() method on my objects (or within a Load method or constructor, doesn't matter) I save a dictionary of the current objects property values like such:

public class MyModel
{
    private Dictionary<string, object> mOriginalValues = new Dictionary<string, object>();

    public void Initialize()
    {
        PropertyInfo[] properties = this.GetType().GetProperties();

        // Save the current value of the properties to our dictionary.
        foreach (PropertyInfo property in properties)
        {
            this.mOriginalValues.Add(property.Name, property.GetValue(this));
        }
    }
}

Pretty easy right? We just use a bit of reflection to grab the current state of the object and store it. Next, later on during the applications run-time when the user presses save, we essentially grab all of the current properties again. This time however, we compare the current properties to the previous ones and return a Dictionary of the properties that changed.

public Dictionary<string, object> GetChanges()
{
    PropertyInfo[] properties = this.GetType().GetProperties();
    var latestChanges = new Dictionary<string, object>();

    // Save the current value of the properties to our dictionary.
    foreach (PropertyInfo property in properties)
    {
        latestChanges.Add(property.Name, property.GetValue(this));
    }

    // Get all properties
    PropertyInfo[] tempProperties = model.GetType().GetProperties().ToArray();

    // Filter properties by only getting what has changed
    properties = tempProperties.Where(p => !Equals(p.GetValue(model, null), model.OrginalValues[p.Name])).ToArray();

    foreach (PropertyInfo property in properties)
    {
        latestChanges.Add(property.Name, property.GetValue(this));
    }

    return latestChanges;
}

If you wanted to, you could either re-initialize the model prior to returning the latest changes, or in the calling method, re-invoke the initialize method to set the models original state to the current state. Essentially, finalizing all of the changes and allowing you to track additional changes once again.

Within your app, you can use if (this.myModel.GetChanges().Count == 0) to determine if the model has changed at all, and therefore provide feedback to the user if they need to save or not. You can use this to compose update statements in SQL so you only update the fields you need, or use this to minimize the amount of data being sent over the cellular data in a Windows Phone 8 app.

This is the complete code I put into a abstract parent class that my objects will inherit from.

public abstract class MyBaseClass 
{
    private Dictionary<string, object> mOriginalValues = new Dictionary<string, object>();

    public void Initialize()
    {
        PropertyInfo[] properties = this.GetType().GetProperties();

        // Save the current value of the properties to our dictionary.
        foreach (PropertyInfo property in properties)
        {
            this.mOriginalValues.Add(property.Name, property.GetValue(this));
        }
    }

    public Dictionary<string, object> GetChanges()
    {
        PropertyInfo[] properties = this.GetType().GetProperties();
        var latestChanges = new Dictionary<string, object>();

        // Save the current value of the properties to our dictionary.
        foreach (PropertyInfo property in properties)
        {
            latestChanges.Add(property.Name, property.GetValue(this));
        }

        // Get all properties
        PropertyInfo[] tempProperties = model.GetType().GetProperties().ToArray();

        // Filter properties by only getting what has changed
        properties = tempProperties.Where(p => !Equals(p.GetValue(model, null), model.OrginalValues[p.Name])).ToArray();

        foreach (PropertyInfo property in properties)
        {
            latestChanges.Add(property.Name, property.GetValue(this));
        }

        return latestChanges;
    }
}

Create objects dynamically in C#

Today I ran into a new class that I had yet to see in the .NET Framework. The ExpandoObject within the System.Dynamic namespace. The class is used as a dynamic object, which I have used in the past.

With a dynamic object, you can do:

static void Main(string[] args)
{
    dynamic car = new Object();
    car.Make = "G35";
    car.Year = 2014;
}

And it would compile, even though the car variable is of a Object type, therefore the Make and Year properties don't exist. This is nice in some cases, but not something that I have really had a large use for as of yet.

Today I learned that you can essentially construct a Type at runtime using the dynamic type. In the example above, the properties that I assigned to the dynamic car object were hard-coded at compile time and not runtime, so they can be used without issue. The .NET Framework ships with an object callec ExpandoObject that allows you to attach properties and methods to a dynamic object during runtime, without recompiling the source.

static void Main(string[] args)
{
    dynamic car = new ExpandoObject();
    car.Make = "G35";
    car.Year = 2014;
}

So what gives? The code above looks the exact same right? With the exception that the dynamic type changed from a object to a ExpandoObject. The ExpandoObject is typed to a dynamic, allowing you to continue to assign properties to the object at compile time. In the event that you want to assign a property to the object at runtime, you invoke the ExpandoObject's IDictionary.Add method.

static void Main(string[] args)
{
    dynamic car = new ExpandoObject();
    car.Make = "G35";
    car.Year = 2014;

    ((IDictionary<string, object>)car).Add("TopSpeed", 180);
}

That essentially adds a new property called "TopSpeed" to the car object and assigns it a value of 180. This can be extremely useful in the event that you are pulling data from an external source such as a local file or a database, and want to construct an object based off of the information loaded. You could in essence do something like this:

dynamic databaseStuff = new ExpandoObject();
foreach (DataColumn column in table.Columns)
{
    ((IDictionary<string, object>)databaseStuff).Add(column.ColumnName, null);
}

Now I have a object who's properties match that of my database Table schema. You can of course assign the value of the column row to the property you just created rather than assigning it to null like I did in my example.

Now, the ((IDictionary<string, object>)someVariable).Add(); method is a real eye sore. You could make that easier by wrapping it.

public class DynamicObject
{
    public dynamic Instance = new ExpandoObject();

    public void AddProperty(string name, object value)
    {
        ((IDictionary<string, object>)this.Instance).Add(name, value);
    }

    public dynamic GetProperty(string name)
    {
        if (((IDictionary<string, object>)this.Instance).ContainsKey(name))
            return ((IDictionary<string, object>)this.Instance)[name];
        else
            return null;
    }
}

With the above code, we can easily add properties to an object at runtime just by invoking the AddProperty method, and retreive the value of the properties either by accessing the dynamic object itself (Instance) or by invoking the GetProperty method. The following code will output the property values to the console. Note that while I am creating the TopSpeed property using our AddProperty method, I am not forced to access it via the GetProperty method, but I can also access it directly from the Instance property since it is a dynamic Type.

    static void Main(string[] args)
    {
        var car = new DynamicObject();
        car.Instance.Make = "G35";
        car.Instance.Year = 2014;

        car.AddProperty("TopSpeed", 180);

        int topSpeed = car.GetProperty("TopSpeed");

        string msg = string.Format("The Top Speed of a {0} is {1}", car.Instance.Make, car.Instance.TopSpeed);
        Console.WriteLine(msg);

        Console.ReadKey();
    }

There are a whole lot of other cool things you could do with this, such as constructing a method at runtime. The above example has been modified to build a method for use at runtime with the car object and a road object. Methods could be obtained by loading code at runtime and assigning methods to a dynamic object as needed. Really useful for application plugins or anything that might need this approach.

We'll start with our wrapper object, by adding a AddMethod method.

    public void AddMethod(Action methodBody, string methodName)
    {
        this.AddProperty(methodName, methodBody);
    }

Since a Action is nothing more than a method delegate, we can attach it as a property and invoke it later. This lets us pass a method into our object and store it as a property. Next, we create a method, add it and invoke it.

    static void Main(string[] args)
    {
        var car = new DynamicObject();
        // Create properties
        car.Instance.Make = "G35";
        car.Instance.Year = 2014;
        car.Instance.CurrentSpeed = 45;

        // Add property in a more dynamic manor.
        car.AddProperty("TopSpeed", 180);
        // Get the property using our wrapper for a more dynamic manor.
        int topSpeed = car.GetProperty("TopSpeed");

        // Access a property we added via our method, directly.
        car.Instance.TopSpeed = 200;

        // Create a Road object.
        var road = new DynamicObject();
        road.AddProperty("SpeedLimit", 65);

        // Add a custom method.
        car.AddMethod(() => { car.Instance.CurrentSpeed = road.Instance.SpeedLimit; }, "MatchSpeedLimit");

        // Invoke our method. Sets the CurrentSpeed (45) to SpeedLimit (65)
        car.Instance.MatchSpeedLimit();
        Console.WriteLine("Current car speed is {0}", car.Instance.CurrentSpeed);

        Console.ReadKey();
    }

That's all there is to it! Of course, you could do all of this directly without the wrapper by using the IDictionary object everywhere, but that's a bit of a pain. I prefer this approach for myself.

The following is the entire source file in full for use.

using System;
using System.Collections.Generic;
using System.Dynamic;

namespace DynamicObjects
{
    public class DynamicObject
    {
        public dynamic Instance = new ExpandoObject();

        public void AddProperty(string name, object value)
        {
            ((IDictionary<string, object>)this.Instance).Add(name, value);
        }

        public dynamic GetProperty(string name)
        {
            if (((IDictionary<string, object>)this.Instance).ContainsKey(name))
                return ((IDictionary<string, object>)this.Instance)[name];
            else
                return null;
        }

        public void AddMethod(Action methodBody, string methodName)
        {
            this.AddProperty(methodName, methodBody);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var car = new DynamicObject();
            // Create properties
            car.Instance.Make = "G35";
            car.Instance.Year = 2014;
            car.Instance.CurrentSpeed = 45;

            // Add property in a more dynamic manor.
            car.AddProperty("TopSpeed", 180);
            // Get the property using our wrapper for a more dynamic manor.
            int topSpeed = car.GetProperty("TopSpeed");

            // Access a property we added via our method, directly.
            car.Instance.TopSpeed = 200;

            // Create a Road object.
            var road = new DynamicObject();
            road.AddProperty("SpeedLimit", 65);

            // Add a custom method.
            car.AddMethod(() => { car.Instance.CurrentSpeed = road.Instance.SpeedLimit; }, "MatchSpeedLimit");

            // Invoke our method. Sets the CurrentSpeed (45) to SpeedLimit (65)
            car.Instance.MatchSpeedLimit();
            Console.WriteLine("Current car speed is {0}", car.Instance.CurrentSpeed);

            Console.ReadKey();
        }
    }
}

Mud Designer Alpha 3 Progress

I have spent the last couple of weeks working on the Mud Designer, revising the code-base some. We had done a pretty good job of writing the engine source for Alpha 2, so in order to do some of my revisions to the source I just had to replace a handful of files rather than a full re-write like we had to do in Alpha 2. While I did re-write a couple of files, the majority of the revisions were made to existing code, allowing me to re-use the bulk of what we wrote.

There are several things within the engine that I wanted to improve on and make changes to. The changes will break any projects using the Alpha 2 engine, but I have always been upfront in regards to the lack of forwards compatibility between versions while in the Alpha stage. Let's take a look at whats changing shall we?

Good bye Codeplex / Hello GitHub

The source control is moving from Codeplex to GitHub. The decision was made due to the engine targetting multiple platforms. It made more sense to host the entire project on GitHub since it will run on OS X, Windows and hopefully mobile devices. Codeplex is typically Windows only software, so the repository location needed to be changed.

Async & Task Parallelism

The engine needed to be revised to make use of the whole new Task Parallelism Library (TPL) Microsoft made available in .NET 4.5. We could not make much use of it originally because of our need to support Windows XP. Unfortunetly when Alpha 3 is released, Windows XP support will be dropped. As of now, Windows 7 holds the majority of the marketshare, and that is what I am going to target.

In order to implement TPL and async stuff, the networking code needed to be revised. Essentially, the server has been re-wrote from the ground up, using TPL instead of System Threads. There probably won't be a big performance increase, but the rest of the engine moving forward will be using TPL so I wanted to ensure that the Server was using the same framework feature set.

R.I.P. IDirector

In Alpha 2, the IDirector interface was used to help abstract away some of the functionality of various things from objects. For instance, the Server had it's player data handling abstracted out and placed into a ServerDirector. The director handled the player connection from the time of connection to the time of disconnect. At the time it made sense to do it this way, but it proved to be a little more difficult to maintain.

In Alpha 3, the player management will be handled by the Server and the Player jointly. The Player Type will implement a new IConnectionState interface that will provide a contract to Player objects for disconnecting and connecting. The Player objects will be responsible for cleaning up their own individual socket connections. Once they are completed, the server will handle the player drop and handle server level clean up. This removes the need for a 3rd object sitting in the middle. Since the Player object has always had a Connection property with a typeof(Socket), it makes sense to have the Player object manage its own disconnect.

This also helps simplify the event wiring that I could not get implemented into Alpha 2. It really did not make sense to have a object fire an event, that traveled to another object. Take the following code for example.

public MyPlayerObject()
{
    this.DisconnectEvent += Player_DisconnectEvent;
}

public void Player_DisconnectEvent()
{
    // My Code here...
    this.Director.Disconnect(this);
}

If a user is making a custom Player object that inherits from BasePlayer and they want to run specific code during a disconnect, they still have to make sure and invoke the server director's Disconnect() method. I wanted to revise this some so that in the future all that they have to write is their specific code and they don't have to pass the Player object off to the director. This will help prevent some issues that can come from this. For instance, what if the Player object cleaned up something that the Server Director still needed to use? Or what if the Server Director cleaned up something that the developer's Player object needed to use? This will prevent that issue form occuring. Another thing with events in C# is that they hardly ever call base and to require a event to always invoke a method in another object that is not base is never really done. Events should technically be added using the += operator, allowing the base event to fire first and the developer event to fire second. While I could have invoked the Server Director method in the base event, I would still run into the issue of the child object trying to access things within the Player object that the Server Director had cleaned up and disconnected.

Essentially in Alpha 2 the Server object worked only as a transfer of authority. The player would connect to the server and the server would just pass the Player object off to the ServerDirector object to manage. In Alpha 3, the Server will maintain control of the Player objects and allow the players to manage themselves for the most part.

States & Commands

I liked the set up put in place for player state management in Alpha 2 but revisions were still needed. In Alpha 2, the flow of control went something like this:

  1. Director renders current state to terminal.
  2. Director Requests the users next command from the current state.
  3. Current state asks the Player object to receive input from the client connection.
  4. Current state attempts to find a Command object that can handle the players input.
  5. Current state instances / invokes the Command object.
  6. Command object performs its action.
  7. Command object changes the Player objects state to a new State.
  8. Loop back at 1.

That is a lot of steps and makes it a real pain to debug and add new functionality. I want to revise this workflow a little bit.

States will no longer be responsible for fetching the next command. The network data is already received within the Player object, so it makes more sense to have the Player object determine the command as well. The current State object uses something along the following lines:

public ICommand GetCommand()
{
    var input = this.Player.ReceiveInput();

    // Determine what command the input correlates to.
}

At the moment, the Player object receives the network input but does nothing with it. Other objects around it take the data and manipulate it. It should be the Player object's responsibility to manage it's own data. When a user enters data, the Player object should parse it and determine what needs to be done. Once it determines what must be done, it can pass the action off to something else at that point. Which is where the Command object will take over.

States will continue to be used, but primarily just to render content to the clients terminal. A Player object will be responsible for switching it's state, but any object can tell the Player object to change it's State from what ever it currently is, to another. Which is essentially how it is set up mostly at the moment.

Data Persistance / Storage

Another major change will be on how the engine stores the current state of the game for saving. Currently, the engine stores everything by serializing the objects out to JSon text files. All of the objects are saved using the FileIO object, which implements the ISavable and ILoadable interfaces. The issue with Alpha 2 was that we never abstracted the save calls. So if a developer wanted to use a MySQL database for storing their data instead of files on the local disk, they would have to trudge through all of the scripts and source files and replace the FileIO calls.

This time around, things are going to be a bit different. I have added a DataContextFactory object that is responsible for fetching all of the Data Context's that can be used for storage. A developer can implement a new storage facility by implementing IDataContext and it will become exposed to the engine automatically. Through out the engine and scripts, the save methods will invoke IDataContext.Save. This allows developers to swap out the actual storage type, such as XML, database or a server someplace, without having to change any of the engine or existing script source code.

In order to achieve this, a lot of the engine save and load code had to be revised. It will work out better in the end, with my ultimate goal being to ship both the original JSon flat-file serialization mode along with a SQLite storage mode for Alpha 3 to help demonstrate how to build custom storage options for your games.

Editor

There are a lot of revisions going on with the engine; due to the changes, the editor has essentially become broken. I was never happy with the editor in the first place and always wanted to do something more dynamic, something that provides better support for custom developer scripted objects. So the Editor is the one piece that will be trashed and re-wrote. I haven't decided how I am going to re-write it yet, but I do know that I am not going to use Windows Forms. I am currently debating between either a WPF app or a web-based app that runs on a local server.

Another thing that I have yet to decide on, is if the Alpha 3 will be held up by the editor re-write or if I will ship Alpha 3 with no editor. Alpha 2 shipped with an editor, but it was still fairly gimped. The engine supported 10x what the editor was actually able to do. When Alpha 2 shipped, there was support for Mobs, items, stats, races, classes and mob appearance customizations. None of which was exposed to the editor due to time constraints. Looking back on it, it kind of sucked to ship something that did not make use of 1/2 of the tech that you had built.

Conclusion

Alpha 3 will be a large improvement over Alpha 2, and will allow the engine development to continue moving forward in a solid direction. Alpha 2 was a huge improvement over the first alpha, and the 3rd version takes Alpha 2 and improves on it even more. I am really looking forward to the next release and getting the engine prepared for the first official Beta. At which point, the engine will be considered feature complete and will just require tweaking, feature improvements and scripted content (for developer references) to be created.

(EOF)

Instance run-time defined objects dynamically in Objective-C

In C# I wrote a nice little feature that allowed users to write custom C# script files that the application's runtime would compile, load and instance during the applications life-cycle. The app even supported modifying or creating new scripts and compiling them, loading and instancing without ever re-starting the application. I did most of this with reflection so it wasn't to hard.

I started thinking about it tonight and thought that it would be neat to implement something like that in Objective-C, just for fun. The goal was to accept a user defined class name, check if it exists and instance it. Once it is instanced, allow for invoking the classes methods. All at runtime.

Another nice thing we could do, is check if the object implements a specific protocol. If you are building game development tools, or wanting to provide an abstract way of instancing objects in your app without having to hard-code all of the different types, you could easily do so. You create a new instance based on what object name is provided (such as a object called "Hydrant" and your user selecting a Hydrant in the game, thus requesting an object called Hydrant), then you verify if it implements one or more protocols such as "Interactable" or "destructible" and then invoke the methods or access the properties that are guaranteed to exist.

The Factory

The Factory will be the heart and soul of this example. It's responsibility is to create the object instances, invoke their methods or access their properties for your models and/or view controllers. Assuming you have created a fresh project, we will create new Objective-C class called Factory, which inherits from NSObject. We will provide it with the following public methods in the header.

@interface OFactory : NSObject

- (id)createObject:(NSString *)objectName;
- (void)invokeMethod:(NSString *)methodName onObject:(id)object;

@end

The first method we will implement is the createObject: method. This method will take a NSString object that hopefully has a valid object name. This could be done by creating another method called objectIsValidForCreation:(NSString *)string; that verifies that the object passed as a string has a matching class with the same name. We can look at that in another post. For now, we assume that the user always passes a string with a objectName that matches an existing class. If not, nil will be returned.

Next we have the invokeMethod: onObject: method which will take a string containing a method name and invoke it on the object supplied as an argument.

Let's implement the createObject: method first in our implememtation file.

#import "Factory.h"
@import ObjectiveC.runtime;

@implementation Factory

- (id)createObject:(NSString *)objectName {
    id objectInstance = [[NSClassFromString(objectName) alloc] init];
    return objectInstance;
}

@end

This is a pretty easy method to implement. We just need to make sure that the ObjectiveC.runtime api is imported. Using the Objective-C runtime we can instance a class by providing it with a NSString object containing the name of the class. The NSClassFromString method does just that. It returns a class, which we then alloc and init. You now can invoke this method like such:

Factory *factory = [[Factory alloc] init];
id testObject = [factory createObject:@"NSDate"];

if ([testObject isKindOfClass:[NSDate class]]) {
    NSLog(@"%@", [testObject description]);
}

When you run that code, you should see the current date printed to the debugger. Pretty cool right?

Next, let's build a simple class called "User" that implements two properties and a initializer. The header looks like this.

@interface User : NSObject
@property (strong, nonatomic) NSString *name;
@property (nonatomic) int age;

- (id)initWithName:(NSString *)name andAge:(int)age;
@end

The method we will implement will be done in the .m implementation file. Let's implement the description method, which is a method belonging to the super class NSObject

@implementation OFTestObject

- (id)init {
    self = [super init];
    if (self) {
        self.name = @"Billy";
        self.age = 33;
    }
    return self;
}

- (id)initWithName:(NSString *)name andAge:(int)age {
    self = [super init];
    if (self) {
        self.name = name;
        self.age = age;
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"The user name is %@ and is %d years old", self.name, self.age];
}
@end

Done. We can use this class to test our next feature, method invoking.

I actually already showed how to do this in my Monitoring Property Changes at Runtime post. There are several changes that I made however to make the implementation more durable in a dynamic environment. This time around it provides support for a unlimited number of arguments that can be passed into the invokeMethod and it returns the same return value that the method you invoked returned.

- (id)invokeMethod:(NSString *)methodName onObject:(id)object withParameter:(id)param, ... {
    if (methodName || object) {
        if ([object respondsToSelector:NSSelectorFromString(methodName)]) {
            // Invoke the getter of the property
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[object class] instanceMethodSignatureForSelector:NSSelectorFromString(methodName)]];
            if (invocation) {
                invocation.target = object;
                invocation.selector = NSSelectorFromString(methodName);

                // Pass the name of the property as the valueForKey: key argument.
                @try {
                    if (param) {
                        // first value is not part of the argument list, so it has to be handled separately.
                        [invocation setArgument:&param atIndex:2];

                        id eachObject;
                        va_list argumentList;

                        va_start(argumentList, param);
                        int index = 3; // Next in the index.
                        while ((eachObject = va_arg(argumentList, id))) {
                            [invocation setArgument:&eachObject atIndex:index];
                            index++;
                        }
                        va_end(argumentList);
                    }

                    id returnValue;
                    [invocation invoke];
                    [invocation getReturnValue:&returnValue];
                    return returnValue;
                }
                @catch (NSException *exception) {
                    NSLog(@"Failed to invoke the method");
                }
            } else {
                NSLog(@"ERROR: Failed to locate the method for @selector:%@", methodName);
            }
        }
    }
    return NULL;
}

Now if you want to test out this code, you can try it with the following code in a view controller some place.

self.factory = [[Factory alloc] init];
id testObject = [self.factory createObject:@"User"];

// user property can be a id, since the class is determined at run time.
self.user = [self.factory invokeMethod:@"description" onObject:testObject withParameter:nil];

The above code will instance a new factory, ask the factory to instance a User class and then invoke that User class method description. If the user class does not exist, nil is returned. In the event that the method does not exist or fails, nil is returned as well. The factory does all of the retrospection required to ensure the app does not crash.

Animate UITableView Data Source changes

Interface Setup

The UITableView has a method called reloadData that essentially removes all of the rows on the UITableView, reconstructs the datasource and then inserts all of the new rows. The issue with releadData is that it happens instantly. If you have an array that your UITableView is using as its datasource, and you remove an object from it, you should really have that object removal be animated. The row should slide out on either the left or right side of the UITableView and everything beneath it slide up.

In this post, I will walk through the steps to achieve that. it's fairly straight forward and will be really easy to reproduce in various different situations that require animating different types of UITableViewCell adjustments.

To start, we need a fresh project. Create a new Single View iOS project called TableView Row Animations and prefix the classes with TRA

This leaves us with a new blank project. Open the story board and add a UITableView to the View, take care that the UITableView does not take up the entire UIView as we need room along the top for another View. The upper portion of the UIView we will add a UISegmentedControl. Give the first index in the UISegmentedControl a title of "Original Data" and give the second index the title "Revised Data". It should look like the following:

Now you need to wire up the UITableView to the TRAViewController. You do that by selecting the UITableView, holding down Control and dragging down to the View Controller icon beneath the View you are editing. Releasing the mouse button will present you with a pop-over box with two options. A delegate and a datasource option; select the datasource and then repeat the process and select the delegate. The following video demonstrates this.

Finally, you need to set up a Action from the UISegmentedControl to your code. Open the assistant editor and control-drag from the UISegmentedControl over to the TRAViewController.m implementation. Create a method called toggleData. Set up a Outlet for your UITableView by control-dragging the UITableView over to your interface, giving it a name of tableView

UITableView Setup

We now have our UI completed, there is nothing left to do here so we can swap over to our TRAViewController.m file and start coding.

The file should be a blank template like the following:

#import "TRAViewController.h"

@interface TRAViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation TRAViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

@end

We will need to add just one property, a NSMutableArray.

#import "TRAViewController.h"

@interface TRAViewController ()
@property (strong, nonatomic) NSMutableArray *data;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation TRAViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

@end

In order for our UITableView to properly work, we also need to tell our View Controller that we are going to conform to two protocols. The UITableViewDataSource and UITableViewDelegate protocols. You can do that by editing the @interface TRAViewController line.

@interface TRAViewController () <UITableViewDataSource, UITableViewDelegate>

As of right now, our app will not run. The UITableView we added will try to invoke two methods that are TRAViewController does not implement yet. We can add them next.

The first method we implement is the numberOfRowsInSection method. The UITableView invokes this method when it's data is loaded/reloaded in order to determine how many rows it needs to provide us with. In order to give it a proper number, we will return the number of items in our data property.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.data count];
}

The next method we invoke is the cellForRowAtIndexPath method. In this method, we will instance a UITableViewCell and assign it a value from our data array based on the current row in the UITableView.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (!cell) 
        cell = [[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    [cell.textLabel setText:[self.data objectAtIndex:indexPath.row]];

    return cell;
}

Datasource setup

We now have the UITableView all set up and working properly. Since we have done nothing with our data property, the UITableView will not do anything. So let's create our initial data; this will be done in our viewDidLoad method.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.data = [[NSMutableArray alloc] init];
    [self.data addObject:@"Test Item 1"];
    [self.data addObject:@"Test Item 2"];
    [self.data addObject:@"Test Item 3"];
    [self.data addObject:@"Test Item 4"];
    [self.data addObject:@"Test Item 5"];
}

Animate datasource changes

Now we can work on the meat of the app, animating changes made to our data. We will implement our toggleData method. In this method, we check which segment is selected and we edit our data based on this.

- (IBAction)toggleData:(UISegmentedControl *)sender {
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];

    // Determine which option is selected.
    // 0 = Original Data; 1 = Revised Data
    if (sender.selectedSegmentIndex == 0) {

        // Tell the table view we are going to update it's data.
        [self.tableView beginUpdates];
        // If original data, we restore our modifed data.
        [self.data insertObject:@"Test Item 1" atIndex:0];
        [self.data insertObject:@"Test Item 3" atIndex:2];
        [self.data insertObject:@"Test Item 5" atIndex:4];

        // Build an array of index's that need to be inserted into the tableview.
        // We match these to the index's we are adding to the data array.
        [indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:0]];
        [indexPaths addObject:[NSIndexPath indexPathForRow:2 inSection:0]];
        [indexPaths addObject:[NSIndexPath indexPathForRow:4 inSection:0]];

        // Next we insert them into the tableview.
        // We slide these rows in from the left.
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];

        // We end our updates.
        [self.tableView endUpdates];
    } else if (sender.selectedSegmentIndex == 1) {
        // Tell the table view we are going to update it's data.
        [self.tableView beginUpdates];

        // If revised data, we delete some items from the datasource.
        // Do this in reverse.
        [self.data removeObjectAtIndex:4];
        [self.data removeObjectAtIndex:2];
        [self.data removeObjectAtIndex:0];

        // Build an array of index's that need to be inserted into the tableview.
        // We match these to the index's we are adding to the data array.
        [indexPaths addObject:[NSIndexPath indexPathForRow:4 inSection:0]];
        [indexPaths addObject:[NSIndexPath indexPathForRow:2 inSection:0]];
        [indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:0]];


        // Next we delete them into the tableview.
        // We slide these rows in from the right.
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];

        // We end our updates.
        [self.tableView endUpdates];
    }
}

You can run this code and watch as the rows are animated in and out of your UITableView very nicely. It should look like the following:

Last notes

You can extend on this by supporting multiple sections in your UITableView if you want. If you have your new data handy, instead of calling reloadData, you can instead perform a beginUpdate, clear your datasource array, invoke the deleteRowsAtIndexPaths: method and then call endUpdates. Once you have done that, you can re-call beginUpdate, add your new data to your datasource array, invoke the insertRowsAtIndexPaths: and then call endUpdates. This will animate the reloading of your data source. This can be used in place of the reloadData method call, which just happens instantly with no animations.