Obviously, with obj-c, there's usually no reason to write getters and setters (thanks to useful mr #synthesize).
So now, needing to do just this, I've come across the problem that I don't know how to write them. :p
I'm sure I'm probably not going about solving my problem the right way - it would be much easier to just subclass my object and such - but I'm trying to write category code to add properties because (in the beginning) it was quicker, and because I wanted to learn how to use category code in my app.
I've got this:
-(BOOL)isMethodStep {
return self.isMethodStep;
}
-(void)setIsMethodStep:(BOOL)theBoolean {
if(self.isMethodStep != theBoolean){
self.isMethodStep = theBoolean;
}
}
and I've tried it without the if query in the setter, but neither seem to work. Loading it with breakpoints shows that for some reason it gets stuck in a continuous loop in the getter method.
Is this code right or am I doing something wrong?
Thanks
Tom
In
-(BOOL)isMethodStep {
return self.isMethodStep;
}
return self.isMethodStep; calls the same isMethodStep method causing an infinite loop. Same thing for setter.
Just use your iVars directly in your accessor method implementations:
-(BOOL)isMethodStep {
return isMethodStep;
}
-(void)setIsMethodStep:(BOOL)theBoolean {
if(isMethodStep != theBoolean){
isMethodStep = theBoolean;
}
}
You don't want to use the self. property syntax within the setter/getter, because that invokes the setter/getter again, instead of directly assigning to the variable.
You need to just say:
-(BOOL)isMethodStep {
return isMethodStep;
}
-(void)setIsMethodStep:(BOOL)theBoolean {
isMethodStep = theBoolean;
}
(assuming "isMethodStep" is the name of your variable). I would omit the test in the setter method too...
Related
I have a NSManagedObject class with two relationships: courseAand courseB.
These relationships should be represented in a dynamic variable. How is it possible to change this variable from outside the class?
#objc(Universtity)
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
}
}
For example from within a ViewController like University.name = University.courseB.name ?
I was thinking about a Notifikation, but this seems maybe a little more complicated as it could be.
And if there is no other way, how should I implement the observer inside the University class?
Thank you for every idea.
Looking at your code, you have declared a "computed" or "ready-only" variable. This is a variable whose value comes from another variable or combination of variables.
I can't see your data model, so it's not clear if you have defined a name parameter in the Core Data model. Regardless, if you have the logic is somewhat confused, because the getter you have defined means any value it may hold would be ignored anyway. You would need to define a setter to set self.courseA.name if you want to ensure the value can be written to. You don't need to worry about key-value coding notifications, because they will be triggered by the Core Data Managed Object.
public class Universtity: NSManagedObject {
dynamic var name: String {
get {
let name = self.courseA?.name
return name!
}
set(newValue) {
courseA!.name = newValue
}
}
}
Also the pattern you have used to force unwrap a non-optional value in your getter isn't optimal. I haven't edited this because that is another discussion, but I would suggest asking yourself the question am I sure why I am doing this? for every "?" and "!" you use.
I have a #interface CustomViewController : UIViewController. I wonder if it is possible to do this:
-(CustomViewController*)parentViewController{
return /* bla bla return custom vc here*/;
}
As you can see, I want to simply override -(UIViewController*)parentViewController but to return an instance of CustomViewController.
Obviously, I can simply create another property like customParentViewContrller and everything will be fine. However, I really don't want to do this, because I will end up using two properties, which actually represent the same thing - not good.
Edit:
Let me clear this. I want to avoid type casting in future so that this code [(CustomViewController*)self.parentViewController someCustomProperty]
turns to this code
[self.parentViewController someCustomProperty].
Yeah you can..
Created a basic project and tested it out:
- (ViewController *)parentViewController {
return self;
}
Working fine.
Consider the following class named SomeClass written in Swift:
#objc class SomeClass: NSObject
{
var shouldCallBar = false
func foo()
{
if (shouldCallBar == true)
{
bar()
}
}
func bar()
{
}
}
For testing the above class foo() method (and similar scenarios mostly written in Objective-C) I was using OCMock like:
- (void) testFooBarShouldBeCalledWhenShouldCallBarIsTrue
{
SomeClass * someClass = [SomeClass new];
// Create mocks.
id mockSomeClass = OCMPartialMock(someClass);
// Expect.
[[mockSomeClass expect] bar];
// Stub.
someClass.shouldCallBar = YES;
// Run code under test.
[someClass foo];
// Verify.
[mockSomeClass verify];
// Stop mocking.
[mockSomeClass stopMocking];
}
But above test fails with Swift code as OCMock won't works well with Swift.
So I am considering something like entirely in Swift:
class SomeClassTests: XCTestCase
{
class MockSomeClass: SomeClass
{
var isBarCalled = false
override func bar()
{
isBarCalled = true
}
}
func testBarShouldBeCalledWhenTrue()
{
let someClass = MockSomeClass()
someClass.shouldCallBar = true
someClass.foo()
XCTAssertTrue(someClass.isBarCalled == true)
}
}
Note here I am subclassing the original class under test and overriding the bar(). I am not at all touching the foo() implementation.
But the downside is I am using MockSomeClass instance to test foo() of SomeClass. This is something I don't like and not recommended.
Is there any better solution to the problem above?
Notes:
I am not talking about Dependency Injection here. Dependency Injection is entirely different approach.
I face these kind of issues when testing UI code in UIViewController.
I have thought of Protocol based programming but was not able to come up with solution to problem above.
So, you want to test that one method (foo) does or does not call another method (bar). The foo method is the one under test, and the bar method is, in the wider sense, a dependent component.
If the invocation of bar has lasting side effects, you could get away with testing that the side effect is/isn't present, maybe by querying a property or similar. In that case you don't need mocks or similar.
If there are no side effects then you must substitute the dependency. To do so you need a seam at which you place code that can tell the test whether the method has been invoked or not. For that, I can only see the two options that Jon already discussed in the question you refer to.
You either put the two methods into separate classes, in which case the class boundary is the seam. Using a protocol, or just an informal convention, you can then completely replace the class that implements bar. Dependency injection comes in handy here.
If the two methods must stay in the same class then you have to use a subclass boundary as a seam, i.e. you use the fact that you can override methods and implement a test-specific sublass. It's easiest when you can use a mock framework. If that's not an option you have to write the code yourself, much like what you describe in your question.
I'm working in Swift and one of the protocols I'm using needs to return an UnsafeMutablePointer<T> of a particular object.
I have something like this:
#objc var myProperty:UnsafeMutablePointer<someObject>
{
get
{
// I call a class function here to get a 'someObject'
// return object which I need to pass back a pointer to it.
return UnsafeMutablePointer<someObject>
}
}
The problem is that Xcode doesn't like this. It complains that '>' is not a unary operator.
I've also tried removing the UnsafeMutablePointer<> and use an & in front of someObject but it complains that the & is to be used immediately in a list of arguments for a function.
I suppose I just can't find the right syntax for this? Any help would be appreciated.
If someObject has the type SomeClass, then you need to update your declaration like this:
#objc var myProperty:UnsafeMutablePointer<SomeClass>
{
get
{
return UnsafeMutablePointer<SomeClass>(unsafeAddressOf(someObject))
}
}
The generic argument needs to be the type of the returned data, and you also need to intialize a specialized UnsafeMutablePointer with the memory address of the desired object.
I have a property that sometimes needs to be a strong reference, and other times needs to be a weak reference. I thought I'd cracked it with the following custom getter/setter:
- (PropertyData *)property
{
return _strongProperty? _strongProperty : _weakProperty;
}
- (void)setProperty:(PropertyData *)newProperty
{
_strongProperty = newProperty;
_weakProperty = nil;
}
- (void)weaken
{
if (_strongProperty != nil) {
_weakProperty = _strongProperty;
_strongProperty = nil;
}
}
Previously there was an ivar called property and an #synthesize property. I removed both and replaced with:
PropertyData __weak *_weakProperty;
PropertyData *_strongProperty;
The class using this class calls weaken when it wants to convert to a weak reference to prevent a retain cycle.
This all works fine on iOS, but running the same code on OS X doesn't work at all. In the debugger, setProperty: has no effect on either of the new ivars right from the outset, and it crashes before weaken is ever called.
I'm confused about whether you need a #synthesize a=b statement when writing custom getter/setters (deployment target OS X 10.10). Not obvious how to do that in this case because there are two backing ivars.
Follow the conventions, or you confuse anyone including yourself.
Start your instance variables with an underscore. Don't use synthesise.
Apart from that, you have two problems. One, calling weaken twice sets the property to nil. Second, there's a good chance that your property has only one reference count and goes away when you call weaken.