Cocoa scripting help when desired data is not held in NSApplication base scripting object - objective-c

I have a cocoa application that I'm trying to make scriptable. It has a model class (subclass of NSObject) including an NSArray property, which holds a number of custom "Element" objects of a separate class. I like this design pattern for this application, because the array property for the model class is not needed outside of that class (and thus I don't want to include it in a subclass/category of NSApplication). However, in all of the examples I have seen for creating a scriptable Cocoa application, the top level scripting object is a subclass or category of NSApplication that includes the exposed data as a property or element.
In contrast, I don't have any properties or methods in NSApplication. As a simplified example, see the code below (from DataModel.h/DataModel in my project):
#import <Foundation/Foundation.h>
#import "Element.h"
#interface DataModel : NSObject
#property (nonatomic) NSArray *elements;
#end
#implementation DataModel
#synthesize elements = _elements;
- (id)init {
if (self= [super init]) {
Element *element1 = [[Element alloc] init];
element1.elementName = "first element";
element1.elementNumber = "22";
Element *element2 = [[Element alloc] init];
element2.elementName = "second element";
element2.elementNumber = "24";
self.elements = [NSArray arrayWithObjects:element1, element2, nil];
}
return self;
}
#end
and this code (for Element.h/Element.m - the objects stored in the "elements" NSArray of the ViewController:
#import <Foundation/Foundation.h>
#interface Element : NSObject {
}
#property (nonatomic) NSString *elementName;
#property (nonatomic) NSString *elementNumber;
#end
#import "Element.h"
#implementation Element
#synthesize elementName = _elementName, elementNumber = _elementNumber;
#end
When the data model is it's own class, how do I make "elements" an accessible property in my sdef file? Do I need an object specifier in the DataModel or the Element class? NSApplication contains no properties, elements, or commands in this case.
Thanks!

Related

What's the best way to unit test a method with a parameter that's immutable and does not have an initializer?

Question
I'm trying to unit test my implementation of a protocol's method that takes an immutable object that's not in my project as a parameter. This object doesn't have any initializers exposed that set its properties. What's the best way to unit test in this scenario?
What I tried
I tried subclassing and casting the properties to readwrite, but you only have access to a super-class' ivars if they're explicitly marked as #protected. Since the class isn't within my project, I can't re-assign a new scope to the ivar.
I also can't mock a setter that doesn't exist, and ivars are not directly writable through mock objects.
Eventually, I decided to add an additional method that the method in question would call, passing only objects whose properties I can set, and I covered that additional method in unit tests.
Is there a better way to unit test in this scenario?
Specifics of my scenario
I'm trying to unit test my implementation of userContentController:didReceiveScriptMessage: from WebKit's WKScriptMessageHandler protocol and can't find a way to pass an instance of WKScriptMessage or of WKUserContentController with any properties set.
To unit test this, I created a new method that takes a parameter of type 'id' and called it from userContentController:didReceiveScriptMessage:, passing WKScriptMessage's body property.
Does this help you?
TestMessage.h
#import <WebKit/WebKit.h>
#interface TestMessage : WKScriptMessage
- (id) initWithBody:(id)body
frameInfo:(WKFrameInfo*)frameInfo
name:(NSString*)name
webView:(WKWebView*)webView;
#end
TestMessage.m
#import "TestMessage.h"
#interface TestMessage()
#property (nonatomic, strong) id messageBody;
#property (nonatomic, strong) WKFrameInfo* messageFrameInfo;
#property (nonatomic, strong) NSString* messageName;
#property (nonatomic, strong) WKWebView* messageWebView;
#end
#implementation TestMessage
- (id) initWithBody:(id)body
frameInfo:(WKFrameInfo*)frameInfo
name:(NSString*)name
webView:(WKWebView*)webView
{
self = [super init];
if (self)
{
_messageBody = body;
_messageFrameInfo = frameInfo;
_messageName = name;
_messageWebView = webView;
}
return self;
}
- (id) body
{
return self.messageBody;
}
- (WKFrameInfo *)frameInfo
{
return self.frameInfo;
}
- (NSString *)name
{
return self.messageName;
}
- (WKWebView *)webView
{
return self.messageWebView;
}
#end
So you're basically creating a subclass with matching properties and then overriding the getters for the superclass properties to return values for the ones you have full access to.
This worked for me with the simple test (I'm sure your scenario is more involved):
- (void) testMessageHandler
{
WKWebView* webView = [[WKWebView alloc] init];
WKUserContentController* controller = [[WKUserContentController alloc] init];
WKFrameInfo* info = [[WKFrameInfo alloc] init];
NSDictionary* testBody = #{#"testKey" : #"testVal" };
TestMessage* testMessage = [[TestMessage alloc] initWithBody:testBody
frameInfo:info
name:#"Message Name"
webView:webView];
// some object conforming to the WKScriptMessageHandler protocol
[self userContentController:controller
didReceiveScriptMessage:testMessage];
}
- (void)userContentController:(nonnull WKUserContentController *)userContentController
didReceiveScriptMessage:(nonnull WKScriptMessage *)message
{
NSLog(#"Received Script Message... (%#)", message.body);
}

Class Method Exposure and Property Definition

I have an academic question about Class Method exposure. There is something that I obviously don't understand about this and would like some clarification from those in the know.
Background:
I have a simple example of two classes named ViewController and ClassB. Class B contains an array with a method named returnArray. The ViewController accesses the array's data. I have exposed the returnArray method in the ClassB.h file.
Question:
Why is it that I can access the array's data in ViewController without having to define a property? I thought that the property would create a getter to allow access to the array. My example (only exposing the method) allows me to access the data without the creation of the #property.
Class Method:
ClassB.h
#interface ClassB : UIViewController
+(NSArray *) returnArray;
//#property (nonatomic, strong) NSArray *returnArray;
ClassB.m
#implementation ClassB
+(NSArray *) returnArray
{
NSArray *locationArray = #[#"Place1", #"Place2"];
return locationArray;
}
ViewController.m
- (void)viewDidLoad
{
NSArray *location = [ClassB returnArray];
NSLog (#"The count of the location is %d", [location count]);
NSLog (#"The second item in testArray is %#", location[1]);
}
Instance method: After reviewing answers
ClassB.h
*/
{
#private
NSArray *returnArray;
}
- (void)setReturnArray:(NSArray*)returnArray;
-(NSArray *) returnArray;
*/
#property (nonatomic, strong) NSArray *returnArray;
#end
ClassB.m - no change
ViewController.h - no change
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//Create instance of ClassB
ClassB *classB = [ClassB new];
//Access the instance of returnArray
NSArray *location = [classB returnArray];
NSLog (#"The count of the location is %d", [location count]);
NSLog (#"The second item in testArray is %#", location[1]);
}
#property is a shorthand notation for creating an instance variable and associated accessor methods (with defined access / modification criteria).
What you have is a class method, which internally creates an array and returns it.
That's why you call [ClassB returnArray]; instead of [instanceOfB array];.
These are completely different things. If you wanted to use a property then you would need to create an instance of ClassB and then access the property. This would work, assuming that the array was created when the instance of ClassB was created.
Wain's answer addresses the difference between #property and Class methods, so it's worth a read. My answer assumes you know the difference between class and instance methods, and focuses on the difference between creating a #property versus creating an instance variable with an associate setter and getter.
The reason is because returnArray is a public method that returns an NSArray object on your ClassB.
A #property is merely a convenient way of creating three things at the same time: an instance variable, a setter, and a getter. It has the added bonus of allowing dot-syntax.
But at the end of the day, dot-syntax aside, all you're doing by declaring a #property is equivalently equal to this:
#interface ClassB : NSObject {
#private
NSArray *returnArray;
}
- (void)setReturnArray:(NSArray*)returnArray;
- (NSArray*)returnArray;
This is the same as this:
#property NSArray *returnArray;
Except of course, the dot syntax.
When you do:
NSArray *myArray = classB.returnArray;
You're not actually directly accessing the array you created when you declared the #property.
What you're doing is calling the getter method that was automatically generated when you declared the #property.

About moving few methods to the superclass

I need to move the same method from 4 different classes to the superclass.
Such methods are exactly the same except for the type of a variable declared in them:
For example, in the method in the first class I have
FirstClass var = [[FirstClass alloc] init]
in the second class
SecondClass var = [[SecondClass alloc] init]
and so on.
What's the best way to implement this variation in the superclass ?
Should I use NSClassFromString in the superclass and get each string from each method in the subclasses?
thanks
I'm not 100% sure I get what you mean. So I could be answering the wrong question
If inside your class you need to use an object (I've called it worker below) to do your work, but the class of this object is not known til later, you can use dependency injection (DI).
MyClass.h
#interface MyClass : NSObject
#property (nonatomic, retain) id<WorkerInterface> worker;
#end
MyClass.m
#implementation MyClass
#synthesize worker = _worker;
- (void)myMethod;
{
[self.worker doSomething];
}
// You could also provide a default class to use if one is not passed in
//
// - (id<WorkerInterface)worker;
// {
// if (!_worker) {
// _worker = [[DefaultWorker alloc] init];
// }
// return _worker;
// }
#end
Now whenever I instantiate this class I can simply pass in the appropriate object to be used e.g:
MyWorkerClass *worker = [[MyWorkerClass alloc] init]; // <- Conforms to #protocol(WorkerInterface)
MyClass *instance = [[MyClass alloc] init];
instance.worker = worker;
[instance doSomething];
If all the different types of iVar's you intend on initializing in the subclasses are descended from a common class, then I'd store that class in the super, or else just store it as an id. Then, setup a property accessor in each of your subclasses the casts the iVar as you need it.
#interface superClass : NSObject{
id _superIvar;
}
#end
#implementation superClass : NSObject
....super's code....
#end
Now in the implementation of the subclass declare a property in a category, shown below (or in the interface, if you want it public)
#interface subClass (private)
#property (strong) ClassType *superIvar;
#end;
#implementation
- (void) setSuperIvar:(ClassType *)superIvar{
_superIvar = superIvar;
}
- (ClassType *) superIvar{
return (ClassType *) _superIvar;
}
- (void) someMethodThatUsesSuperIvar{
[self.superIvar doSomething];
}
#end
Alternatively, if you don't want to open your _superIvar to direct access, you can set a property on the superclass and access through the property on the subclass. But in this way you can easily access super's ivars cast to the appropriate type.

Accessing NSMutableDictionary Across Classes

I have declared an NSMutableDictionary object in AppController.h and initialized in the corresponding AppController.m file.
AppController.h
#import <Cocoa/Cocoa.h>
#interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
AppController.m
#import "AppController.h"
#implementation AppController
- (id)init
{
uberDict = [NSMutableDictionary new];
return self;
}
Now I want to use the NSMutableDictionary object in another view, flashcardView. I add/remove items in the dictionary using methods in the AppController class and want to use the same dictionary (with the current items still present in it) in the flashcardView view. The problem is that I don't know how to access the dictionary object from outside AppController. How would I do that?
from flashcardView.m
- (void)setAndCheckString
{
NSArray *keys = [uberDict allKeys];
NSString *i;
for (i in keys) {
string = i;
NSLog(#"%#", string);
}
}
Here's where the problem lies. What do I do with uberDict to make this work? Thanks!
While I encourage you to look at alternative design patterns, to do what you're looking for you simply need to add a method (or property) to access uberDict to AppController. As a property, the code would be:
#interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
#property (readonly) NSMutableArray *uberDict;
#end
in the AppController.h file, and just add a one line #synthesize uberDict; inside the AppContoller implementation (before the #end). Don't worry about the (readonly) -- this means that the object getting the uberDict cannot set it to a new dictionary, but still can modify the contents of the dict and read from it.

#Synthesize array of class objects?

Having some difficulty with what I thought would be straight forward. I am trying to make an array of class objects but running into different problems. The goal was to create one class that held an array of another class of objects.
Any help appreciated:
// Basic class unit
#interface MobRec : NSObject {
NSString *MName;
int Speed;
}
#end
// Master Class holding an array of units
#interface MobDefs : NSObject {
MobRec *MobInfo;
}
#property(retain) MobRec *MobInfo;
#end
#synthesize MobInfo;
1) From reading it seems I should create and NSMutableArray but how do you declare an NSMutableArray of custom class objects? All iterations I try cause errors. Previously I had predefined the size in the class as MobInfo[20]; but that didnt seem to be good for anything.
2) How do you properly #Synthesize an array of class objects?
I think you misunderstand what #synthesize does. It creates accessor methods to get and set the property (i.e., it would create a getter method to return that NSMutableArray and a setter method to allow you to replace it with another NSMutableArray). To create an NSMutableArray, you would just create one like any other object in that class's initializer.
NSMutableArray doesn't have any type checking as you add (or read) from it, so you can add any objects you want to it.
In this case I'd have something like:
// MobRec Class
#interface MobRec : NSObject {
NSString *mName;
int speed;
}
#property(retain)NSString *name;
#property(assign)int speed;
#end
#implementation MobRec
#synthesize mName, speed;
#end
// MobDefs Class
#import "MobRec.h"
#interface MobDefs : NSObject {
NSMutableArray *mobInfo;
}
#property(retain) NSMutableArray *mobInfo;
#end
#implementation MobDefs
#synthesize mobInfo;
- (id)init {
mobInfo = [[NSMutableArray alloc] init];
MobRec *aNewMobRec = [[MobRec alloc] init];
[mobInfo addObject:aNewMobRec];
[aNewMobRec release];
}
I've included the basics for adding to the array as well so you can see how its used. Oh and don't forget you have to release the MobInfo in the dealloc method.
But mostly look at NSMutableArray
Your MobDefs class is not necessary, you can use an NSMutableArray directly. NSArray can hold objects of any type, and is declared in just the same way as any other object (such as your MName property).